Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 743
avimehenwal Avatar asked Feb 15 '13 11:02

avimehenwal


People also ask

How do I run a Windows shell command in Python?

The naive approach to run a shell command is by using os. system(): Let's first create a new Python file called shell_cmd.py or any name of your choice. Second, in the Python file, import the os module, which contains the system function that executes shell commands.

Can I use Python to execute shell commands?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

How do you run a shell command from Python and get the output?

In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE , and returning just the stdout attribute. You can pass stderr=subprocess. STDOUT to ensure that error messages are included in the returned output.


1 Answers

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 (because I don't have access to any Windows machines), 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.

Also note that @bluescorpion says in the comments that Windows 10 needs a trailing backslash, as in check_output("dir C:\\", shell=True). The double backslash is needed because \ is a special character in python, so it has to be escaped. (Also note that even prefixing the string with r doesn't help if \ is the very last character of the string — r"dir C:\" is a syntax error, though r"dir C:\ " is not.)

like image 108
Mike Avatar answered Sep 21 '22 09:09

Mike