How can we interact with OS shell using Python ?
I want to run windows cmd commands via python. How can it be achieved ?
How can we interact with OS shell using Python ? I want to run
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The newer
subprocess.check_outputand similar commands are supposed to replaceos.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:check_outputreturns a string of the output from your command. Alternatively,subprocess.calljust 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
bytesoutput. If you want to change this into a string, you need something likeIf 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 withrdoesn’t help if\is the very last character of the string —r"dir C:\"is a syntax error, thoughr"dir C:\ "is not.)