2014年12月16日 星期二

[ Python 常見問題 ] Running shell command from python and capturing the output

Source From Here 
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 
subprocess.check_output(args, *, stdin=None, stder...lse, universal_newlines=False):
Run command with arguments and return its output as a byte string.

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: 
  1. output = Popen(["mycmd""myarg"], stdout=PIPE).communicate()[0]  
Or 
>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo

If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin
>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo

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 DEVNULLto get communicate to work at all.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...