How to spawn a new independent process in Python

£可爱£侵袭症+ 提交于 2019-11-27 22:01:36
Lasse

Try prepending "nohup" to script.sh. You'll probably need to decide what to do with stdout and stderr; I just drop it in the example.

import os
from subprocess import Popen

devnull = open(os.devnull, 'wb') # Use this in Python < 3.3
# Python >= 3.3 has subprocess.DEVNULL
Popen(['nohup', 'script.sh'], stdout=devnull, stderr=devnull)
Steve Barnes

Just use subprocess.Popen. The following works OK for me on Windows XP / Windows 7 and Python 2.5.4, 2.6.6, and 2.7.4. And after being converted with py2exe - not tried 3.3 - it comes from the need to delete expired test software on the clients machine.

import os
import subprocess
import sys
from tempfile import gettempdir

def ExitAndDestroy(ProgPath):
    """ Exit and destroy """
    absp = os.path.abspath(ProgPath)
    fn = os.path.join(gettempdir(), 'SelfDestruct.bat')
    script_lines = [
        '@rem Self Destruct Script',
        '@echo ERROR - Attempting to run expired test only software',
        '@pause',
        '@del /F /Q %s' % (absp),
        '@echo Deleted Offending File!',
        '@del /F /Q %s\n' % (fn),
        #'@exit\n',
        ]
    bf = open(fn, 'wt')
    bf.write('\n'.join(script_lines))
    bf.flush()
    bf.close()
    p = subprocess.Popen([fn], shell=False)
    sys.exit(-1)

if __name__ == "__main__":
   ExitAndDestroy(sys.argv[0])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!