2011-09-08 28 views

答えて

37

サブプロセスドキュメントセクション"Replacing shell pipeline"で説明したように、subprocess.PIPEを使用:

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 

私がやろうとしています何のPerlの同等のようなものになるだろう

cat file.log | tail -1 

は、コマンドのようなものだったと仮定します

またはこれが動作するはずです:

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

のインタプリタを呼び出すために必要であり、 2番目の解決策を働かせてください。最初の解決策を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もキャプチャしたい場合は、task.communicate()を使用する必要があります。 task.stdout.read()を呼び出してからtask.stderr.read()を実行すると、stderrのバッファがいっぱいになるとデッドロックする可能性があります。それらを結合したい場合は、2>&1をシェルコマンドの一部として使用できるはずです。

しかし、あなたの正確な場合を考えると、

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またはstdinを設定する必要はありませんより良いフォーマットについて
  • 、それが出力
  • 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] 
関連する問題