![](/img/trans.png)
[英]How do I kill all other running python processes without killing the parent process
[英]Kill child process without killing parent
我正在使用os.system()運行python程序,並試圖將其輸出記錄到文件中。 這很好。
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()
問題是myprogram.py調用了另一個python程序,該程序為我提供了我需要的輸出但沒有完成-我什至可以看到提示符變得不同,如下圖所示
當我進入嘗試使用os.system(“ quit()”)和subprocess.popen(“ quit()”,shell = False)的程序的下一行時,有沒有辦法殺死子進程?什么也沒做。
我不能真正使用exit(),因為那樣會一起殺死python。
順便說一下,這攤位
f=subprocess.Popen("myprogram.py -arg1 > outputfile.txt") and then
f.communicate() #this just stalls because the child program does not end.
由myprogram.py
調用的程序myprogram.py
您放置在python提示符下。 除非您向我們展示代碼,否則我們無法告訴您原因。
使用subprocess
模塊(這是更通用的)是優選使用os.system
。
但是您沒有正確使用子流程。 像這樣嘗試:
with open('outputfile.txt', 'w+') as outf:
rc = subprocess.call(['python', 'myprogram.py', '-arg1'], stdout=outf)
一旦subprocess.call
完成, with
語句將關閉文件。 該程序及其參數應以字符串列表形式給出。 重定向是通過使用std...
參數實現的。
myprogram.py
完成后, rc
包含其返回碼。
如果要捕獲程序的輸出,請改用subprocess.check_output()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.