-2

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?

CopyrightC
  • 857
  • 2
  • 7
  • 15

4 Answers4

1
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

python
  • 36
  • 2
0

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

David
  • 8,113
  • 2
  • 17
  • 36
0

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

Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
0

There is already a similar question here: Running shell command and capturing the output

import subprocess
output = subprocess.check_output(["echo", "Hello, World!"])
Lucas
  • 11
  • 3