简体   繁体   中英

Kill child process without killing parent

I am using os.system() to run a python program and am trying to log its output to the file. This works fine.

os.system("myprogram.py -arg1 -arg2 > outputfile.txt")
#something here to kill/cleanup whatever is left from os.system()
#read outputfile1.txt- this output file got all the data I needed from os.system()

The problem is that myprogram.py calls another python program which gives me the output i need but doesn't finish- I can even see the prompt become different as in the picture below

在此处输入图片说明

Is there a way to kill the child process when I get to the next line of my program I tried using os.system("quit()") and subprocess.popen("quit()", shell=False) and that didn't do anything.

I can't really use exit() because that just kills python all together.

Btw this stalls

f=subprocess.Popen("myprogram.py -arg1 > outputfile.txt") and then 
f.communicate() #this just stalls because the child program does not end. 

The program that is being called by myprogram.py lands you in the python prompt. Why that happens we cannot tell you unless you show us the code.

Using the subprocess module (which is more versatile) is preferred to using os.system .

But you're not using subprocess correctly. Try it like this:

with open('outputfile.txt', 'w+') as outf:
    rc = subprocess.call(['python', 'myprogram.py', '-arg1'], stdout=outf)

The with statement will close the file once subprocess.call is done. The program and its arguments should be given as a list of strings. Redirection is achieved by using the std... arguments.

After myprogram.py finishes, rc contains its return code.

If you want to capture the output of the program, use subprocess.check_output() instead.

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