如何使用pexpect.spawn在后台运行命令?

时间:2016-01-21 10:55:31

标签: python python-2.7 pexpect

我有一个代码片段,我在后台运行命令:

from sys import stdout,exit
import pexpect
try:
           child=pexpect.spawn("./gmapPlayerCore.r &")
except:
           print "Replaytool Execution Failed!!"
           exit(1)
child.timeout=Timeout
child.logfile=stdout
status=child.expect(["[nN]o [sS]uch [fF]ile","",pexpect.TIMEOUT,pexpect.EOF])
if status==0:
           print "gmapPlayerCore file is missing"
           exit(1)
elif status==1:
           print "Starting ReplayTool!!!"
else:
           print "Timed out!!"

此处,脚本退出后,spawn中的进程即使在后台运行也会被杀死

如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

您要求生成的子项是同步的,以便您可以执行child.expect(…)和异步&。这些彼此并不一致。

你可能想要:

child=pexpect.spawn("./gmapPlayerCore.r") # no &
status=child.expect(["[nN]o [sS]uch [fF]ile","",pexpect.TIMEOUT,pexpect.EOF])
child.interact()

其中interact定义为:

  

这将子进程的控制权交给交互式用户(键盘上的人)。 ...