在Python中以编程方式执行和终止长时间运行的批处理
我一直在寻找一种在 python 中启动和终止长时间运行的“批处理作业”的方法。现在我正在使用“os.system()”在每个子进程内启动长时间运行的批处理作业。正如您可能已经猜到的,“os.system()”在该子进程(孙进程?)内生成一个新进程,因此我无法从祖进程中终止批处理作业。为了提供我刚刚描述的内容的一些可视化:
Main (grandparent) process, with PID = AAAA
|
|------> child process with PID = BBBB
|
|------> os.system("some long-running batch file)
[grandchild process, with PID = CCCC]
所以,我的问题是我无法从祖父母那里杀死孙子进程...
我的问题是,有没有办法在子进程内启动长时间运行的批处理作业,并且能够通过终止子进程来终止批处理作业吗? 我可以使用 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...
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 ?
Thanks !!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
subprocess 模块是生成和控制进程的正确方法在Python中。
来自文档:
所以...如果您在Python 2.4+,
subprocess
是os.system
的替代品,用于停止进程,请查看
terminate()
和communicate()
方法。Popen
对象的subprocess module is the proper way to spawn and control processes in Python.
from the docs:
so... if you are on Python 2.4+,
subprocess
is the replacement foros.system
for stopping processes, check out the
terminate()
andcommunicate()
methods ofPopen
objects.如果您使用的是 Posix 兼容系统(例如 Linux 或 OS X)并且子进程后无需运行任何 Python 代码,请使用 os.execv。一般来说,避免使用
os.system
并使用subprocess
模块。If you are on a Posix-compatible system (e.g., Linux or OS X) and no Python code has to be run after the child process, use
os.execv
. In general, avoidos.system
and use thesubprocess
module instead.如果您想控制子进程的启动和停止,则必须使用线程。在这种情况下,只需看看 Python 的
threading
模块。If you want control over start and stop of child processes you have to use threading. In that case, look no further than Python's
threading
module.