Running windows shell commands with python
Solution 1
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.)
Solution 2
You would use the os module system method.
You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC
For example:
os.system('python') opens up the windows command prompt and runs the python interpreter
Solution 3
Refactoring of @srini-beerge's answer which gets the output and the return code
import subprocess
def run_win_cmd(cmd):
result = []
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
if errcode is not None:
raise Exception('cmd %s failed, see above for details', cmd)
Solution 4
Simple Import os package and run below command.
import os
os.system("python test.py")
Solution 5
You can use the subprocess
package with the code as below:
import subprocess
cmdCommand = "python test.py" #specify your cmd command
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print output
![avimehenwal](https://i.stack.imgur.com/M2lYl.jpg?s=256&g=1)
avimehenwal
Computer Engineer exploring new technologies and trying to understand them better. Technology appretiator and kneen learner. Javascript, Python developer. New to web developmetn and designing. Love artistic and creative job :D
Updated on July 08, 2022Comments
-
avimehenwal almost 2 years
How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
-
Anonsage over 9 yearsSidetip: Use
alt+prtscr
to just get a screenshot of the active window. ;) -
Bill N about 9 yearsThis works in Windows 7. Thanks. It does return \r\n at the end of the string, so you might need to strip that out with a
[0:-2]
substring. -
Mike about 9 yearsUsing
[0:-2]
for that purpose makes me nervous. If anyone takes that code to apply it in a non-Windows context, they'll certainly change the obviousdir C:
tols
or whatever. But they could easily fail to realize that[0:-2]
should be changed to[0:-1]
. I'd recommend.rstrip()
instead, which would work on any platform (unless you want to capture other trailing whitespace), and also makes the reason behind the string alteration clearer. -
Nevin Raj Victor about 9 years@Mikw: I have a windows command which is used for deployment.Just a single line of command. How can I call it from an external python3.4 script
-
Mike about 9 yearsJust use the code above, but replace
dir C:
with whatever your single line of code is. -
Igor over 8 yearsThanks for this tip. Although documentation recommends using subprocess module, I find this more pythonic for simple tasks.
-
Mike almost 7 yearsI don't have access to any windows machines, but I'm guessing you're using python 3. If so, you might want to look into the
universal_newlines
argument. -
blue scorpion over 6 yearsWorks in Win 10 with a slight modification: check_output("dir C:\\", shell=True)
-
DDay about 5 yearsUsing shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases. It also helps in escaping the backslashes for Windows use. See the note in the Python documentation. docs.python.org/3/library/subprocess.html#popen-constructor