How to start a background process in Python?

后端 未结 7 586
庸人自扰
庸人自扰 2020-11-22 02:44

I\'m trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background

7条回答
  •  后悔当初
    2020-11-22 03:16

    Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

    https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

    import os, time, sys, subprocess
    
    if len(sys.argv) == 2:
        time.sleep(5)
        print 'track end'
        if sys.platform == 'darwin':
            subprocess.Popen(['say', 'hello'])
    else:
        print 'main begin'
        subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
        print 'main end'
    

提交回复
热议问题