【问题标题】:Kill child process without killing parent杀死子进程而不杀死父进程
【发布时间】:2013-03-28 23:04:39
【问题描述】:

我正在使用 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. 

【问题讨论】:

    标签: python windows


    【解决方案1】:

    myprogram.py 正在调用的程序使您进入 python 提示符。为什么会发生这种情况,除非您向我们展示代码,否则我们无法告诉您。

    使用subprocess 模块(更通用)优于使用os.system

    但是您没有正确使用子流程。试试这样:

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

    with 语句将在 subprocess.call 完成后关闭文件。程序及其参数应作为字符串列表给出。重定向是通过使用std... 参数实现的。

    myprogram.py 完成后,rc 包含其返回码。

    如果要捕获程序的输出,请改用subprocess.check_output()

    【讨论】:

    • 我也遇到了同样的问题。 python 提示出现,甚至 rc.kill() 或 rc.terminate() 什么都不做。
    • 我是否可以将quit() 发送给子进程留下的孩子(python 提示符?)
    • 如果孩子留下 python 提示符,说明有问题。尝试修复而不是解决它。
    • 好的,谢谢.. 会的。通过执行 -subprocess.Popen("taskkill /F /T /PID %i"%rc.pid, shell=True) 确实找到了临时解决方法
    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2011-09-09
    • 2016-01-24
    相关资源
    最近更新 更多