擅长:python、mysql、java
<p>我知道这个问题已经有一段时间没有问过了,但我偶然发现了这个问题,我想我会自愿为我工作。</p>
<p>我基本上只是设置了一个while循环,询问进程是否完成,然后如果进程从未完成,则抛出一个错误。这样我就有了一个更灵活的等待,它会以一种对我更有意义的方式出错,同时不会把我的自动化搞得太糟。</p>
<p>我还应该指出,这是在程序退出之前等待一系列交互提示结束时执行的操作。所以,如果你在等待一个过程中的某件事,那么这个方法就不会那么有效了。但是,您可能可以修改它来处理不同的情况。</p>
<pre><code>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)
</code></pre>