How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
相关问题
- 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
If you need the output from the command you are calling, then you can use subprocess.check_output (Python 2.7+).
Also note the shell parameter.
This is how I run my commands. This code has everything you need pretty much
Update:
subprocess.run
is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)Here's some examples from the docs.
Run a process:
Raise on failed run:
Capture output:
Original answer:
I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.
Example usage from the readme:
Pipe stuff around too:
It can be this simple:
use the os module
eg
If you want to return the results of the command, you can use
os.popen
. However, this is deprecated since version 2.6 in favor of the subprocess module, which other answers have covered well.