简体   繁体   English

脚本结束后,Python Windows脚本子进程继续输出

[英]Python windows script subprocess continues to output after script ends

Hi I am writing a python script in windows and using subprocess 嗨,我正在Windows中编写python脚本并使用子过程

I have a line like 我有一条线

results=subprocess.Popen(['xyz.exe'],stdout=subprocess.PIPE) results = subprocess.Popen(['xyz.exe'],stdout = subprocess.PIPE)

After the script ends, and I get back to the promp carrot in cmd, I see more output from the script being printed out. 脚本结束后,回到cmd中的提示胡萝卜,我看到了脚本输出的更多内容。 I'm seeing stuff like 我看到类似的东西

Could Not Find xxx_echo.txt 找不到xxx_echo.txt

Being printed out repeatedly. 被反复打印出来。

How do I properly close the subprocess in windows? 如何正确关闭Windows中的子进程?

Could Not Find xxx_echo.txt looks like an error message, which would likely be printed on stderr. Could Not Find xxx_echo.txt看起来像一条错误消息,可能会打印在stderr上。 Your call to Popen() does not collect the child's stderr output, so it will be printed in your terminal. 您对Popen()调用不会收集孩子的stderr输出,因此它将在您的终端中打印。

If your script does not wait for the child to complete, the child may still be executing after your script has exited. 如果脚本不等待子进程完成,则退出脚本后,子进程可能仍在执行。 You should call wait() to wait for the child to complete execution. 您应该调用wait()以等待子进程完成执行。 If you don't want to wait, call terminate() to terminate the child process. 如果您不想等待,请调用terminate()终止子进程。

You should also collect the stderr if you don't want it dumped to the terminal. 如果您不希望将stderr丢弃到终端,也应该收集它。

child = subprocess.Popen(['xyz.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
child.wait()
print child.returncode

您需要在退出主脚本之前调用result.kill()或results.terminate()(在Windows上是别名)以结束子流程。

You have to call the terminate() method: 您必须调用terminate()方法:

results.terminate()

There is also kill() for stuck sub-processes. 卡住的子进程也有kill()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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