python stdout用法_Python中,使用文件作为stdin和stdout的子进程

Specifically, how do I replicate the following batch command using python subprocess module?:

myprogram myoutput.out

If you don't know, I am trying to run myprogram using the contents of myinput.in as the standard input and myoutput.out as standard output.

(myprogram is written in c and I/O with scanf, printf)

So far I have tried the following:

myinput = open('myinput.in')

myout = open('myoutput.out')

p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput, shell=True)

p.wait()

myoutput.flush()

And also,

myinput = open('myinput.in')

myout = open('myoutput.out')

inputs = myinput.read()

myinput.close()

myprogram = subprocess.Popen('myprogram.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True)

outputs = myprogram.communicate(input=inputs)[0]

myout.write(str(outputs))

myout.close()

Neither one of these writes anything to output, however when I run my batch command, it works like a charm. :/ Please tell me I'm missing something obvious.

解决方案

The error messages from python should tell you exactly what is going wrong:

you open myoutput.out read only

it is opened as myout but then you use myoutput

Also, shell=True is unnecessary here.

The following should work:

myinput = open('myinput.in')

myoutput = open('myoutput.out', 'w')

p = subprocess.Popen('myprogram.exe', stdin=myinput, stdout=myoutput)

p.wait()

myoutput.flush()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值