[英]Executing shell command in python with file as stdin
在我的Python代碼中,我有
executable_filepath = '/home/user/executable'
input_filepath = '/home/user/file.in'
我想從命令分析shell中的輸出
/home/user/executable </home/user/file.in
我試過了
command = executable_filepath + ' <' + input_filepath
p = subprocess.Popen([command], stdout=subprocess.PIPE)
p.wait()
output = p.stdout.read()
但它不起作用。 我現在能想到的唯一解決方案是創建另一個管道,並通過它復制輸入文件,但必須有一個簡單的方法。
from subprocess import check_output
with open("/home/user/file.in", "rb") as file:
output = check_output(["/home/user/executable"], stdin=file)
您需要在對Popen
的調用中指定shell=True
。 默認情況下, [command]
直接傳遞給exec
系列中的系統調用,該系列調用不了解shell重定向運算符。
或者,您可以讓Popen
將進程連接到該文件:
with open(input_filepath, 'r') as input_fh:
p = subprocess.Popen( [executable_filepath], stdout=subprocess.PIPE, stdin=input_fh)
p.wait()
output=p.stdout.read()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.