簡體   English   中英

Python 在標准輸入上打開發送到進程,在標准輸出上接收

[英]Python Popen sending to process on stdin, receiving on stdout

我將命令行上的可執行文件傳遞給我的 python 腳本。 我做了一些計算,然后我想將這些計算的結果在 STDIN 上發送到可執行文件。 完成后,我想從 STDOUT 中獲取可執行文件的結果。

ciphertext = str(hex(C1))
exe = popen([sys.argv[1]], stdout=PIPE, stdin=PIPE)
result = exe.communicate(input=ciphertext)[0]
print(result)

當我打印result時,我什么也沒得到,而不是空行。 我確信可執行文件可以處理數據,因為我在命令行上使用“>”重復了相同的操作,結果與先前計算的結果相同。

一個有效的例子

#!/usr/bin/env python
import subprocess
text = 'hello'
proc = subprocess.Popen(
    'md5sum',stdout=subprocess.PIPE,
    stdin=subprocess.PIPE)
proc.stdin.write(text)
proc.stdin.close()
result = proc.stdout.read()
print result
proc.wait()

要獲得與“ execuable < params.file > output.file ”相同的功能,請執行以下操作:

#!/usr/bin/env python
import subprocess
infile,outfile = 'params.file','output.file'
with open(outfile,'w') as ouf:
    with open(infile,'r') as inf:
        proc = subprocess.Popen(
            'md5sum',stdout=ouf,stdin=inf)
        proc.wait()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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