在python中,我想做以下事情: 我有一个命令行程序,要求用户逐步输入输入&等待,以获得结果。现在,我想使用python自动执行此过程。
过程将类似于:
有没有办法在python中模拟这个过程?我知道我们可以运行一个程序&使用os.open()或subprocess传入命令行参数。但这些都是一次性的事情。
由于
答案 0 :(得分:3)
您可以使用subprocess模块和Popen.communicate()
将数据发送到进程stdin
编辑:
你是对的,他应该使用stdin.write
发送数据,如下所示:
#!/usr/bin/env python
import subprocess
import time
print 'Launching new process...'
p = subprocess.Popen(['python', 'so1.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print 'Sending "something"...'
p.stdin.write('something\n')
print 'Waiting 30s...'
time.sleep(30)
print 'Sending "done"...'
p.stdin.write('done\n')
p.communicate()
print '=o='
答案 1 :(得分:2)
在Unix上,或在Windows上使用cygwin python,pexpect模块可以自动执行交互式程序。
请参阅examples here。对于需要五分钟的部分,您需要将超过默认timeout
的参数传递给expect()
。