Python Popen在stdin上发送以进行处理,在stdout上进行接收 [英] Python Popen sending to process on stdin, receiving on stdout

查看:518
本文介绍了Python Popen在stdin上发送以进行处理,在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时,我什么也没得到,不是无,而是空行.我确信可执行文件可以处理数据,因为我在命令行上使用>"重复了相同的操作,并且具有相同的先前计算的结果.

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()

要获取与"execuable < params.file > output.file"相同的内容,请执行以下操作:

to get the same thing as "execuable < params.file > output.file", do this:

#!/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在stdin上发送以进行处理,在stdout上进行接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆