How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With