2011-09-08 33 views

回答

37

使用subprocess.PIPE,如子文檔部分"Replacing shell pipeline"解釋說:

import subprocess 
p1 = subprocess.Popen(["cat", "file.log"], stdout=subprocess.PIPE) 
p2 = subprocess.Popen(["tail", "-1"], stdin=p1.stdout, stdout=subprocess.PIPE) 
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. 
output,err = p2.communicate() 

或者使用sh module,管道變得composition of functions

import sh 
output = sh.tail(sh.cat('file.log'), '-1') 
1

此:

import subprocess 
p = subprocess.Popen("cat file.log | tail -1", shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) 
#Try shell=True if the above doesn't work with shell=False 
p_stdout = p.stdout.read() 
p_stderr = p.stderr.read() 
print p_stdout 

或者這應該工作:

import os 
result = os.system("cat file.log | tail -1") 
+0

我可以獲得第二個解決方案。嘗試使用Python 2.6.7的第一個解決方案時,Popen行上出現一個錯誤,錯誤信息是「OSError:[Errno 2] No such file or directory」。不清楚爲什麼會發生這種情況。 – spudATX

+0

嘗試使用'file.log'的絕對路徑。或者,嘗試'shell = True'。 – chown

+0

'shell = False'應該是'shell = True' – retracile

5
import subprocess 
task = subprocess.Popen("cat file.log | tail -1", shell=True, stdout=subprocess.PIPE) 
data = task.stdout.read() 
assert task.wait() == 0 

注這不會捕獲stderr。如果您還想捕獲stderr,則需要使用task.communicate();如果填充stderr緩衝區,則調用task.stdout.read(),然後task.stderr.read()可能會死鎖。如果你想將它們組合起來,你應該可以使用2>&1作爲shell命令的一部分。

但考慮到您的具體情況,

task = subprocess.Popen(['tail', '-1', 'file.log'], stdout=subprocess.PIPE) 
data = task.stdout.read() 
assert task.wait() == 0 

避免了管在所有的需要。

1

另一個類似於POPEN方式將是:

command=r"""cat file.log | tail -1 """ 
output=subprocess.check_output(command, shell=True) 
0

這是從@chown叉子與一些改進:

  • import subprocess一個別名,設置參數
  • 時使得更容易
  • 如果您只是想要輸出,您在撥打時無需設置stderr
  • 更好的格式,建議到輸出
  • shell=True是必要的,解碼爲了調用解釋爲命令行

#!/usr/bin/python3 

import subprocess as sp 

p = sp.Popen("cat app.log | grep guido", shell=True, stdout=sp.PIPE) 

output = p.stdout.read() 
print(output.decode('utf-8')) 

$ cat app.log 
2017-10-14 22:34:12, User Removed [albert.wesker] 
2017-10-26 18:14:02, User Removed [alexei.ivanovich] 
2017-10-28 12:14:56, User Created [ivan.leon] 
2017-11-14 09:22:07, User Created [guido.rossum] 

$ python3 subproc.py 
2017-11-14 09:22:07, User Created [guido.rossum] 
相關問題