在不杀死paren的情况下杀死子进程

2024-06-17 11:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用操作系统()运行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()

问题是我的程序.py调用另一个python程序,它提供了我需要的输出,但没有完成-我甚至可以看到提示变得不同,如下图所示

enter image description here

当我进入程序的下一行时,有没有办法终止子进程 我试着用操作系统(“quit()”)和子流程.popen(“quit()”,shell=False)但这没有任何作用。在

我不能真正地使用exit(),因为这只会把python一起杀死。在

顺便说一句,这个暂停了

^{pr2}$

Tags: 文件frompy程序txthereos记录
1条回答
网友
1楼 · 发布于 2024-06-17 11:58:28

myprogram.py调用的程序将使您进入python提示符。为什么会这样,除非你给我们看密码,否则我们无法告诉你。在

使用subprocess模块(它更通用)比使用os.system更好。在

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

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

一旦with完成,with语句将关闭文件。程序及其参数应该以字符串列表的形式给出。重定向是通过使用std...参数实现的。在

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

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

相关问题 更多 >