Avi Mehenwal Avi Mehenwal - 3 months ago 31
Bash Question

Running windows shell commands with python

How can we interact with OS shell using Python ?
I want to run windows cmd commands via python. How can it be achieved ?


The newer subprocess.check_output and similar commands are supposed to replace os.system. See this page for details. While I can't test this on Windows, the following should work:

from subprocess import check_output
check_output("dir C:", shell=True)

check_output returns a string of the output from your command. Alternatively, subprocess.call just runs the command and returns the status of the command (usually 0 if everything is okay).

Also note that, in python 3, that string output is now bytes output. If you want to change this into a string, you need something like

from subprocess import check_output
check_output("dir C:", shell=True).decode()

If necessary, you can tell it the kind of encoding your program outputs. The default is utf-8, which typically works fine, but other standard options are here.