简体   繁体   中英

Run python subprocess using Popen independently

I wanted to run execute a python script as a UNIX shell command independently using python Popen .

Script1.py : This script will take multiple arguments. Script2.py : This script will parse some conditions and will prepare necessary arguments needed to call Script1.py

Assume Script2.py parsed some conditions and prepared a command to run Script1.py Command : python Script1.py arg1 arg2 arg3

Currently running the script as :

proc=subprocess.Popen(Command,shell=True,stdout=None, stderr=None)

But, when I kill Script2.py manually(using CTRL+C), I could see that Script1.py is also getting killed/Terminated.

How can I run Script1.py independently without worrying about status of Script2.py ?

The way to detach a process from its parent on window$ is:

from subprocess import Popen

CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
Popen(['python', 'drive:/path/to/loop_test.py', 'some_arg', 'another_arg'],
                 stdin=None, stdout=None, stderr=None, shell=True,
                 creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
                 )

On linux you should be able to achieve the same using nohup and preexec_fn=os.setpgrp , ie:

Popen(['nohup', 'python', '/path/to/loop_test.py', 'some_arg','another_arg'],
shell=True, stdout=None, stderr=None, preexec_fn=os.setpgrp )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM