Terminate a python script from another python script

前端 未结 2 1341
我寻月下人不归
我寻月下人不归 2020-11-29 11:22

I\'ve got a long running python script that I want to be able to end from another python script. Ideally what I\'m looking for is some way of setting a process ID to the fi

2条回答
  •  一整个雨季
    2020-11-29 11:56

    You're looking for the subprocess module.

    import subprocess as sp
    
    extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py 
    
    status = sp.Popen.poll(extProc) # status should be 'None'
    
    sp.Popen.terminate(extProc) # closes the process
    
    status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)
    

    subprocess.Popen starts the external python script, equivalent to typing 'python myPyScript.py' in a console or terminal.

    The status from subprocess.Popen.poll(extProc) will be 'None' if the process is still running, and (for me) 1 if it has been closed from within this script. Not sure about what the status is if it has been closed another way.

提交回复
热议问题