Python Popen在stdin上发送到进程,在stdou上接收

2024-04-30 04:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在命令行上将一个可执行文件传递给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时,我什么也得不到,不是没有,而是空行。我确信可执行文件可以处理这些数据,因为我在命令行上使用“>;”重复了相同的操作,结果与前面的计算结果相同。


Tags: 命令行脚本可执行文件stdinstdoutresultexepopen
1条回答
网友
1楼 · 发布于 2024-04-30 04:13:03

一个有效的例子

#!/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()

相关问题 更多 >