title: How to correctly handle autorun start & stop on linux with python
body: <p>I have two scripts: "autorun.py" and "main.py". I added "autorun.py" as service to the autorun in my linux system. works perfectly!</p>
  
  <p>Now my question is: When I want to launch "main.py" from my autorun script, and "main.py" will run forever, "autorun.py" never terminates as well! So when I do</p>
  
  <pre><code>sudo service autorun-test start
  </code></pre>
  
  <p>the command also never finishes!</p>
  
  <p>How can I run "main.py" and then exit, and to finish it up, how can I then stop "main.py" when "autorun.py" is launched with the parameter "stop" ? (this is how all other services work I think)</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Solution:</p>
  
  <pre><code>if sys.argv[1] == "start":
      print "Starting..."
      with daemon.DaemonContext(working_directory="/home/pi/python"):
          execfile("main.py")
  else:
      pid = int(open("/home/pi/python/main.pid").read())
      try:
          os.kill(pid, 9)
          print "Stopped!"
      except:
          print "No process with PID "+str(pid)
  </code></pre>