在 python 中以编程方式执行和终止一个长时间运行的批处理

问题描述

我一直在寻找一种在 python 中启动和终止长期运行的批处理作业"的方法.现在我正在使用os.system()"在每个子进程中启动一个长时间运行的批处理作业.正如您可能已经猜到的那样,os.system()"会在该子进程(孙进程?)中生成一个新进程,因此我无法从祖父进程中终止批处理作业.为我刚才描述的内容提供一些可视化:

I have been searching for a way to start and terminate a long-running "batch jobs" in python. Right now I'm using "os.system()" to launch a long-running batch job inside each child process. As you might have guessed, "os.system()" spawns a new process inside that child process (grandchild process?), so I cannot kill the batch job from the grand-parent process. To provide some visualization of what I have just described:

Main (grandparent) process, with PID = AAAA
          |
          |------> child process with PID = BBBB
                         |
                         |------> os.system("some long-running batch file)
                                  [grandchild process, with PID = CCCC]

所以,我的问题是我无法从祖父母那里杀死孙子进程...

So, my problem is I cannot kill the grandchild process from the grandparent...

我的问题是,有没有办法在子进程中启动长时间运行的批处理作业,并且能够通过终止子进程来终止该批处理作业?我可以使用 os.system() 的替代方法来终止主进程中的批处理作业吗?

My question is, is there a way to start a long-running batch job inside a child process, and being able to kill that batch job by just terminating the child process? What are the alternatives to os.system() that I can use so that I can kill the batch-job from the main process ?

谢谢!!


解决方案

subprocess 模块是在 Python 中生成和控制进程的正确方法.

subprocess module is the proper way to spawn and control processes in Python.

来自文档:

子流程模块允许您产生新的进程,连接到他们的输入/输出/错误管道,并获得他们的返回码.这个模块打算替换其他几个,较旧的模块和功能,例如:

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:

os.system
os.spawn
os.popen
popen2
命令

os.system
os.spawn
os.popen
popen2
commands

所以...如果您使用的是 Python 2.4+,subprocessos.system

so... if you are on Python 2.4+, subprocess is the replacement for os.system

要停止进程,请查看 Popen 对象的 terminate()communicate() 方法.

for stopping processes, check out the terminate() and communicate() methods of Popen objects.

相关文章