python管道只有标准输入,输出一次,怎么办两次或更多次 [英] python pipe only stdin,out once, how to do twice or more time

查看:303
本文介绍了python管道只有标准输入,输出一次,怎么办两次或更多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

成功的python管道标准输入,仅此源一次

success python pipe stdin, out only one time this source

main.py

import subprocess from subprocess import PIPE, STDOUT

player_pipe = subprocess.Popen(["source\call.py", 'arg1'], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=True)

player_pipe.stdin.write("Send Msg\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.kill()
player_pipe.wait()

call.py

import sys

getMsg = raw_input()
print getMsg

但是我想要两次或更多次标准输入时间

but I want twice or more time stdin, out

因此请更新源,但不起作用

so update source but it's not work

此来源出了什么问题

main.py(更新无效)

main.py (update-not work)

import subprocess from subprocess import PIPE, STDOUT

player_pipe = subprocess.Popen(["source\call.py", 'arg1'], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=True)

player_pipe.stdin.write("Send Msg\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.stdin.write("Send Msg2\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.kill()
player_pipe.wait()

call.py(更新无效)

call.py(update-not work)

import sys

getMsg = raw_input()
print getMsg

getMsg2 = raw_input()
print getMsg2

:D

推荐答案

call.py的输出已缓冲.因此您必须flush()将其发送到main.py.

the output of call.py is buffered. so you have to flush() it to send to main.py.

#!/usr/bin/python2
import sys

getMsg = raw_input()
print getMsg
sys.stdout.flush()

getMsg2 = raw_input()
print getMsg2
sys.stdout.flush()

请注意,至少当您的操作系统是Linux时,您需要shebang #!/usr/bin/python2(我不知道为什么OP的代码在没有shebang的情况下才能工作.也许有些Windows魔术?).

Note that you need shebang #!/usr/bin/python2 at least when your OS is Linux (I don't know why OP's code works without shebang. Maybe some Windows magic ?).

还可以使用-u选项不缓冲python的输出.

Also you can use -u option not to buffer the output of python.

player_pipe = subprocess.Popen(["/usr/bin/python2","-u","./call.py"], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=False)

这篇关于python管道只有标准输入,输出一次,怎么办两次或更多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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