How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- How to get the return code of a shell script in lu
- Evil ctypes hack in python
Refactoring of @srini-beerge's answer which gets the output and the return code
You can use the
subprocess
package with the code as below:The newer
subprocess.check_output
and similar commands are supposed to replaceos.system
. See this page for details. While I can't test this on Windows, the following should work: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 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.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