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

What's wrong this source

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(update-not work)

import sys

getMsg = raw_input()

print getMsg

getMsg2 = raw_input()

print getMsg2

:D

解决方案

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

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 ?).

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值