Question
I want to write a function that will execute a shell command and return it's output as a string, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.
How-To
For convenience, Python 2.7 provides the
which takes the same arguments as Popen, but returns a string containing the program's output. You can pass stderr=subprocess.STDOUT to ensure that error messages are included in the returned output -- but don't pass stderr=subprocess.PIPE, which can cause deadlocks.
If you're using an older python, Vartec's method will work. But the better way to go -- at least in simple cases that don't require real-time output capturing -- is to use communicate. As in:
- output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin:
Finally, note Aaron Hall's answer, which indicates that on some systems, you may need to set stdout, stderr, and stdin all to PIPE (or DEVNULL) to get communicate to work at all.
沒有留言:
張貼留言