0

I have a code snippet in which I run a command in background:

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!!"

Here, after the script exits the process in the spawn also gets killed even though it is run in background

How to achieve this?

Ramana Reddy
  • 369
  • 1
  • 8
  • 28
  • 2
    The `&` is not doing anything - that's bash syntax to run a process in the background, and you're not running it through bash. I think that if you pass `preexec_fn=os.setsid` when spawning the child, that should detach it from its controlling tty, and prevent it getting killed. Or if you can modify the code in the subprocess, you could make it ignore SIGHUP. – Thomas K Jan 21 '16 at 17:46

1 Answers1

2

You are asking the spawned child to be synchronous so that you can execute child.expect(…) and asynchronous &. These don't agree with each other.

You probably want:

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

where interact is defined as:

This gives control of the child process to the interactive user (the human at the keyboard). …

msw
  • 42,753
  • 9
  • 87
  • 112