Running windows shell commands with python
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.)
How do I execute a program or call a system command?
Use the subprocess
module in the standard library:
import subprocess
subprocess.run(["ls", "-l"])
The advantage of subprocess.run
over os.system
is that it is more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, etc...).
Even the documentation for os.system
recommends using subprocess
instead:
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call
instead of .run
:
subprocess.call(["ls", "-l"])
How to run cmd.exe commands from python?
use the subprocess
module.
Python 2: https://docs.python.org/2/library/subprocess.html
example:
import subprocess
subprocess.call('ConverterApp.exe', 'file1.x', 'file1.y'])
Python 3: https://docs.python.org/3/library/subprocess.html
you can still use subprocess.call
, but for Python versions >3.4, it's preferred to use the newer subprocess.run
.
example:
import subprocess
subprocess.run(['ConverterApp.exe', 'file1.x', 'file1.y'])
Note: in both subprocess.call
, and subprocess.run
, your command should be passed as a sequence (i.e. a list).
Running command lines within your Python script
You should use the subprocess module. In particular, subprocess.call will run command line programs for you.
How to execute a command prompt command from python
You probably want to try something like this:
command = "cmd.exe /C dir C:\\"
I don't think you can pipe into cmd.exe
... If you are coming from a unix background, well, cmd.exe
has some ugly warts!
EDIT: According to Sven Marnach, you can pipe to cmd.exe
. I tried following in a python shell:
>>> import subprocess
>>> proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> stdout, stderr = proc.communicate('dir c:\\')
>>> stdout
'Microsoft Windows [Version 6.1.7600]\r\nCopyright (c) 2009 Microsoft Corporatio
n. All rights reserved.\r\n\r\nC:\\Python25>More? '
As you can see, you still have a bit of work to do (only the first line is returned), but you might be able to get this to work...
Related Topics
How to Redirect Stdout to Both File and Console with Scripting
How to Access the Request Object or Any Other Variable in a Form's Clean() Method
How to Add a Background Thread to Flask
How to Validate a Date String Format in Python
How to Exchange Keys with Values in a Dictionary
Check If String Ends with One of the Strings from a List
Ipython Reads Wrong Python Version
Running an Outside Program (Executable) in Python
How to Override the Copy/Deepcopy Operations for a Python Object
Matplotlib: Annotating a 3D Scatter Plot
Attributeerror: 'Module' Object Has No Attribute 'Urlopen'
How to Stop a Looping Thread in Python
How to Pass Optional Parameters to a Function
Expand Python Search Path to Other Source
Python 3.7 Anaconda Environment - Import _Ssl Dll Load Fail Error
Applying Udfs on Groupeddata in Pyspark (With Functioning Python Example)
Is There a Python Equivalent of the C# Null-Coalescing Operator