簡體   English   中英

在python中執行shell命令,文件為stdin

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM