Python pexpect未按预期工作

2024-04-30 05:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,运行一些外壳命令与模拟用户数据。

问题是,如果代码末尾没有这一行,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')

Tags: thetochildreadinputrawstdoutsys
2条回答

我知道这个问题已经有一段时间没有问过了,但我偶然发现了这个问题,我想我会自愿为我工作。

我基本上只是设置了一个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)

问题似乎是,如果不使用raw_输入来减慢程序的速度,您的python脚本将在子进程完成之前退出(并终止进程中的子进程)。

我认为pexpect.wait()应该可以处理这种情况,但从the documentation听起来,如果子进程退出后有未读的输出,wait()将挂起,并且在不知道子进程详细信息的情况下,我不能说是否会发生风险。read()和wait()的某些组合可能会起作用,或者如果很难确定您可以只计时.sleep()几秒。

相关问题 更多 >