我正在尝试编写一个运行一些带有模拟用户数据的shell命令的程序。
问题是如果代码末尾没有这一行,shell命令就无法正常运行:
raw_input('press <enter> to exit')
我怎样摆脱那条线?
child = pexpect.spawn('grunt init:gruntfile')
child.logfile_read = sys.stdout
child.expect ('Is the DOM involved in ANY way?')
child.sendline ('y')
child.logfile_read = sys.stdout
child.expect ('Will files be concatenated or minified?')
child.sendline ('y')
child.logfile_read = sys.stdout
child.expect ('Will you have a package.json file?')
child.sendline ('y')
child.logfile_read = sys.stdout
child.expect ('Do you need to make any changes to the above before continuing?')
child.sendline ('n')
child.logfile_read = sys.stdout
raw_input('press <enter> to exit')
答案 0 :(得分:6)
问题似乎是如果没有raw_input来减慢程序的速度,你的python脚本会在子进程完成之前退出(并在进程中终止子进程)。
我认为pexpect.wait()
应该处理这种情况,但是如果在子进程退出后有未读输出,并且不知道你的详细信息,则the documentation听起来像wait()会挂起孩子的过程我不能说是否会有风险发生。 read()和wait()的某种组合可能会起作用,或者如果想出这个问题就太麻烦了,你只需要time.sleep()几秒钟。
答案 1 :(得分:0)
我知道问这个问题已经有一段时间了,但是我遇到了这个问题,以为我会自愿为我工作。
我基本上只是设置一个while循环,询问该过程是否完成,如果从未完成,则会抛出错误。这样,我将有一个更灵活的等待,以对我更有意义的方式出错,同时又不会使我的自动化工作变得很糟糕。
我还应该指出,这是为了在程序退出之前,在一系列交互式提示的末尾等待执行某项操作。因此,如果您正在等待过程中的某些东西,那么效果就不太好了。但是,您可能可以对其进行修改以应对不同的情况。
import time, sys, pexpect
some_function():
child = pexpect.spawn('some command here')
if debugging: # Just in case you also want to see the output for debugging
child.logfile = sys.stdout
# Do stuff
child expect('some regex')
child sendline('some response')
sleep_count = 0 # For tracking how long it slept for.
acceptable_duration = 120 # The amount of time that I'm willing to wait
# Note that apparently solaris can take a while to reply to isalive(),
# so the process may go a lot longer than what you set the duration to.
while child.isalive():
if sleep_count > acceptable_duration
sys.stderr.write("Useful text explaining that the process never exited."
sys.exit(1)
time.sleep(1)