How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
-
1Related: [Is it possible to use python as a shell replacement?](http://programmers.stackexchange.com/q/182077) – Martijn Pieters Feb 15 '13 at 11:54
7 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.)

- 19,114
- 12
- 59
- 91
-
This 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. – Bill N Apr 17 '15 at 18:49
-
7Using `[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 obvious `dir C:` to `ls` or whatever. But they could easily fail to realize that `[0:-2]` should be changed to `[0:-1]`. I'd recommend [`.rstrip()`](https://docs.python.org/2/library/stdtypes.html#str.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. – Mike May 18 '15 at 14:11
-
@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 – Nevin Raj Victor Jun 04 '15 at 04:54
-
Just use the code above, but replace `dir C:` with whatever your single line of code is. – Mike Jun 04 '15 at 05:02
-
I 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](https://docs.python.org/3.6/library/subprocess.html#frequently-used-arguments). – Mike Jun 26 '17 at 13:38
-
2Works in Win 10 with a slight modification: check_output("dir C:\\", shell=True) – blue scorpion Nov 15 '17 at 16:56
-
Using 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. https://docs.python.org/3/library/subprocess.html#popen-constructor – DDay May 02 '19 at 20:14
-
-
1@codingbruh Yes. In fact (as I noted in a previous comment), I don't even have access to any windows machines. I use it routinely on macOS and various species of linux without any trouble. You just need to give it commands that the shell will understand — e.g., `ls /` instead of `dir C:`. – Mike Nov 21 '22 at 21:10
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
-
14Sidetip: Use `alt+prtscr` to just get a screenshot of the active window. ;) – Anonsage Jan 20 '15 at 08:28
-
Thanks for this tip. Although documentation recommends using [subprocess module](https://docs.python.org/3.4/library/os.html#os.system), I find this more pythonic for simple tasks. – Igor Feb 09 '16 at 17:48
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)

- 8,487
- 6
- 54
- 53
Simple Import os package and run below command.
import os
os.system("python test.py")

- 289
- 4
- 10
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

- 1,735
- 16
- 19
import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
print line
result.append(line)
errcode = process.returncode
for line in result:
print line

- 5
- 1
- 4
This worked for me, although you don't need to use import subprocess
just in case you need to work with adb.
from tkinter import *
import os
# import subprocess
root = Tk()
root.title("Shutdown PC")
root.geometry("500x500")
def button():
os.system('timeout /T 10 /nobreak')
os.system('SHUTDOWN/s')
b = Button(root, text="SHUTDOWN PC", width=30, height=2, command = button)
b.pack()
root.mainloop()

- 11
- 3