パイプを含むシェルコマンドを呼び出して出力をキャプチャする方法はありますか?パイプを含むコマンドラインを実行し、結果をSTDOUTに表示
my $string = `cat file.log | tail -1`;
パイプを含むシェルコマンドを呼び出して出力をキャプチャする方法はありますか?パイプを含むコマンドラインを実行し、結果をSTDOUTに表示
my $string = `cat file.log | tail -1`;
サブプロセスドキュメントセクション"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')
この:
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
cat file.log | tail -1
:
は、コマンドのようなものだったと仮定します
またはこれが動作するはずです:
import os
result = os.system("cat file.log | tail -1")
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
は全くパイプの必要性を回避します。
popenのに似たもう一つの方法は、次のようになります。
command=r"""cat file.log | tail -1 """
output=subprocess.check_output(command, shell=True)
これは、いくつかの改善と @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]
のインタプリタを呼び出すために必要であり、 2番目の解決策を働かせてください。最初の解決策をPython 2.6.7で試してみると、私はPopen行でエラーが発生し、 "OSError:[Errno 2] No such file or directory"というエラーが表示されます。なぜこれが起こっているのか不明です。 – spudATX
'file.log'の絶対パスを使ってみてください。あるいは、 'shell = True'を試してみてください。 – chown
'shell = False'は' shell = True'でなければなりません – retracile