Python Popen 发送到标准输入处理,接收标准输出 [英] Python Popen sending to process on stdin, receiving on stdout
问题描述
我将命令行上的可执行文件传递给我的 python 脚本.我做了一些计算,然后我想将 STDIN 上的这些计算结果发送到可执行文件.完成后,我想从 STDOUT 获取可执行文件的结果.
I pass an executable on the command-line to my python script. I do some calculations and then I'd like to send the result of these calculations on STDIN to the executable. When it has finished I would like to get the executable's result back from STDOUT.
ciphertext = str(hex(C1))
exe = popen([sys.argv[1]], stdout=PIPE, stdin=PIPE)
result = exe.communicate(input=ciphertext)[0]
print(result)
当我打印 result
时,我什么也没得到,不是 None,而是一个空行.我确信可执行文件可以处理数据,因为我在命令行上使用>"重复了同样的事情,并且得到了相同的先前计算结果.
When I print result
I get nothing, not None, an empty line. I'm sure that the executable works with the data as I've repeated the same thing using the '>' on the command-line with the same previously calculated 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()
获得与executable <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()
这篇关于Python Popen 发送到标准输入处理,接收标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!