Is there a way through which I can pass the output of a CMD command to a .txt
file using python?
Something like this:
import os
os.system('cmd /c "netsh wlan show profiles"')
#output=OUTPUT
output_file=open(outputfile+'.txt','w')
output_file.write(OUTPUT)
output_file.close()
Is there a way to do this?
import subprocess
out = subprocess.getoutput("ls -l")
print(out)
Now you can just pass on this output to a txt
file using open()
and file.read()
method
You can just pass the output to a temporary file. The following is a simple example:
import os
os.system('cmd /c "netsh wlan show profiles" > tmp.txt')
Then you can just read the tmp.txt file and see the output. This solution is based on your code.
There are other options such as using subprocess
, you can read more in the following link: https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module
Try this library https://docs.python.org/3/library/subprocess.html
Method subprocess.run()
should do the job. It allows to capture stdout and stderr when param capture_output=True
There is already a similar question here: Running shell command and capturing the output
import subprocess
output = subprocess.check_output(["echo", "Hello, World!"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.