我正在尝试编写一个程序来运行一些带有模拟用户数据的 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')
最佳答案
问题似乎是没有 raw_input 来减慢程序速度,您的 python 脚本在子进程完成之前退出(并杀死进程中的子进程)。
我认为 pexpect.wait()
应该可以处理这种情况,但它听起来来自 the documentation如果在子进程退出后有未读输出,wait() 将挂起,并且在不知道您的子进程的详细信息的情况下我不能说是否存在会发生的风险。 read() 和 wait() 的某种组合可能会起作用,或者如果弄清楚它太麻烦,您可以只使用 time.sleep() 几秒钟。
关于Python pexpect 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10380309/