Python wrapper script to let a program be executed remotely with no blocking
Question: I am looking for a wrapper script to run a program which is called remotely by
a SSH command which terminates without waiting for the result of the program.

Here is my code:

    
    
    #!/usr/bin/python
    
    import sys
    import os, subprocess
    
    def main():
       print "PID_last_child", os.getpid()
       argpass = ['main_p.py']
       for a in sys.argv:
            if a.find("wrapper.py") == -1: 
                argpass.append(a)
       pid = subprocess.Popen(argpass).pid
       print "PID for the actual process: ", pid
    
    
    if __name__ == "__main__":
    
      print "PID_MAIN:", os.getpid()
    
      try: 
             pid = os.fork() 
             print "FORK1: ", pid 
             if pid > 0: 
                   sys.exit(0)
       except OSError, e:  
             print >>sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror)
             sys.exit(1)
    
       os.chdir('/') 
       os.setsid()
       os.umask(0) 
    
       try:
             pid = os.fork() 
             print "FORK2: ", pid 
             if pid > 0: 
                    sys.exit(0)
       except OSError, e:  
             print >>sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror)
             sys.exit(1)
    
       main() 
    

I suppose using double forking, i should be able to do that... but no luck so
far.

Any thoughts on this is greatly appreciated.


Answer: I fully credit this link for the answer in bash syntax: [How to starting
process as daemon using ssh command?](http://www.unix.com/shell-programming-
scripting/70523-how-starting-process-daemon-using-ssh-command.html)

You don't even need to double-fork. The issue is that the stdout is still
connected. Here is the python approach:

**wrapper.py**

    
    
    import subprocess
    import os
    
    def main():
        pid = subprocess.Popen(['nohup', '/path/to/main_p.py'], 
                                stdout = open(os.devnull, 'w+', 0),
                                stderr = subprocess.STDOUT
                                ).pid
        print pid
    
    if __name__ == "__main__":
    
        main() 
    

And then the ssh command would call this wrapper:

    
    
    ssh server /path/to/wrapper.py
    

You just need to redirect stdout -> devull, and the process will return right
away.

