Run an independent process using python

This is a really simple question, but I cannot find any solution.

I have a python script and I want to start an independent daemon process. I want to call ym python script, run this dameon system tray, do some python magic in the database file and exit, leaving the daemon in the system tray.

I tried os.system , subprocess.call , subprocess.Popen , os.execl , but it always supports my script until I close the system daemon.

It seems like it should be a simple solution, but I can't get something to work.

EDIT: Windows Solution: os.startfile() http://docs.python.org/library/os.html?highlight=startfile#os.startfile

Sometimes refusing a request means that you are just about to answer.

+6
source share
3 answers

Windows Solution: os.startfile()

It works as if you double-clicked the executable file and ran it independently. Very comfortable one liner.

http://docs.python.org/library/os.html?highlight=startfile#os.startfile

+1
source

I would recommend using the double-fork method.

Example:

 import os import sys import time def main(): fh = open('log', 'a') while True: fh.write('Still alive!') fh.flush() time.sleep(1) def _fork(): try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, 'Unable to fork: %d (%s)' % (e.errno, e.strerror) sys.exit(1) def fork(): _fork() # remove references from the main process os.chdir('/') os.setsid() os.umask(0) _fork() if __name__ == '__main__': fork() main() 
+2
source

You can use a couple of excellent Popen parameters to execute a really disconnected process on Windows (thanks to greenhat for his answer here ):

 import subprocess DETACHED_PROCESS = 0x00000008 results = subprocess.Popen(['notepad.exe'], close_fds=True, creationflags=DETACHED_PROCESS) print(results.pid) 

See also this answer for a great cross-platform version (be sure to add close_fds , although this is very important for Windows).

0
source

Source: https://habr.com/ru/post/920985/


All Articles