1

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

2 回答 2

6

问题似乎是,如果没有 raw_input 来减慢程序速度,您的 python 脚本在子进程完成之前退出(并杀死进程中的子进程)。

我认为应该处理这种情况,但是从文档pexpect.wait()中听起来,如果子进程退出后有未读的输出,wait() 会挂起,并且在不知道子进程的详细信息的情况下,我不能说是否存在是会发生的风险。read() 和 wait() 的某种组合可能会起作用,或者如果很难弄清楚你可以 time.sleep() 几秒钟。

于 2012-04-30T08:13:09.683 回答
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)
于 2018-11-14T17:53:13.820 回答