Python pexpect 没有按预期工作

标签 python shell pexpect

我正在尝试编写一个程序来运行一些带有模拟用户数据的 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/

相关文章:

python - 为什么不在 Python 函数内部的返回函数上使用括号?

linux - Bash - grep 问题

linux - 如何在分割 fastq 文件时附加变量名称?

linux - 为什么 dd 不能处理 shell 脚本中的稀疏文件?

python - 使用 pexpect (python) 时 SFTP 未完成文件传输

python - Pexpect,运行 ssh-copy-id 在尝试生成第二个进程时挂起

python - 双迭代线构造

python - 使用 pandas read_csv 读取这个以制表符分隔的文件时,行丢失

python - 为 Python 列表赋值不起作用?

python - 预计 setecho 不工作