[英]Understanding subprocess module in python when running program from python script
I usually run a program from my OpenSuse linux terminal by typing ./run file_name
. 通常,我通常在OpenSuse linux终端中通过输入./run file_name
来运行程序。 This will bring up a series of options that I can choose from by typing a numeric value 0-9
and hitting return on my keyboard. 这将带来一系列选项,我可以通过键入数字0-9
并按键盘上的return来选择。 Now I want to do this from a python script automatically. 现在,我想从python脚本自动执行此操作。 My example below is not working, but I can't understand where I'm failing and how to debug: 我下面的示例无法正常工作,但是我无法理解失败的地方以及调试方法:
import subprocess
p = subprocess.Popen(["/path/to/program/run", file_name], stdin = subprocess.PIPE,stdout=subprocess.PIPE,shell=False)
print "Hello"
out, err = p.communicate(input='0\r\n')
print out
print err
for line in p.stdout.readlines():
print line
The output of this program is just 这个程序的输出是
>> Hello
>>
ie then it seems to freeze (I have no idea whats actually happening!) I would have expected to see what I see when I run ./run file_name
and hit 0
and then return
directly in my terminal, but I assure you this is not the case. 即然后它似乎冻结了(我不知道实际发生了什么!)我本来希望看到我在运行./run file_name
并单击0
然后直接在终端中return
时看到的内容,但是我向您保证这不是案子。 What can I do to debug my code? 我该如何调试我的代码?
Edit 1: as suggested in comments 编辑1:如评论中所建议
import subprocess
fileName = 'test_profile'
p = subprocess.Popen(["/path/to/program/run", fileName], stdin = subprocess.PIPE,stdout=subprocess.PIPE,shell=False)
print "Hello"
for line in iter(p.stdout.readline,""):
print line
will indeed return the stdout of my program! 确实会返回我程序的标准输出!
communicate
waits for the completion of the program. communicate
等待程序完成。 For example: 例如:
import subprocess
p = subprocess.Popen(["cut", "-c2"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell=False)
out, err = p.communicate(input='abc')
print("Result: '{}'".format(out.strip()))
# Result: 'b'
It sounds like you have a more interactive script, in which case you probably should try out pexpect
听起来您的脚本更具交互性,在这种情况下,您可能应该尝试使用pexpect
import pexpect
child = pexpect.spawn('cut -c2')
child.sendline('abc')
child.readline() # repeat what was typed
print(child.readline()) # prints 'b'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.