subprocess的输入输出处理

本文介绍使用Python的subprocess模块进行应用程序交互的方法,并提供两个案例。案例一演示了简单的输入输出操作;案例二则展示了如何实现连续输入输出。文章还提到了在实际应用中遇到的问题:在某些情况下,对Popen对象的stdin进行多次写入操作时,只有第一次写入有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在用Python处理一些应用程序的交互,subprocess的Popen可以实现应用的stdin和stdout交互,但在实际使用过程中,Popen的stdin并不是经常work。

下面是Mark别人的代码,在Python2.7.x下测试通过。

1,Case1 简单输出

#test1.py  
import sys  
line = sys.stdin.readline()  
print 'test',line
sys.stdout.flush()

#run1.py
from subprocess import *
proc =Popen('test1.py', stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=True)
string = 'say hi\n'
proc.stdin.write(string)
line = proc.stdout.readline()
print(line)
proc.stdout.flush()

在命令行下运行 python run1.py,得到打印如下:

> test say hi


2, Case 2 连续输入输出

# test2.py
import sys
while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line)
    sys.stdout.flush()

# run2.py
import sys
from subprocess import *
proc = Popen('test2.py',stdin=PIPE,stdout=PIPE,stderr=STDOUT,shell=True)

line = raw_input()
while line != 'q':
    proc.stdin.write(line + '\n')
    proc.stdin.flush()
    output = proc.stdout.readline()
    sys.stdout.write(output)
    sys.stdout.flush()
    line = raw_input()

在命令行下,运行 python run2.py,然后可不停的输入,得到相同的输出,直至输入字符‘q'退出程序。


以上两个是用于学习的Case,在某个实际应用中发现,获取Popen的stdin后,第一次write成功,再次write时就不起作用了,但应用程序依旧运行,未得到预期效果,纳闷了~

Mark一下,希望尔后能解释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值