以编程方式执行和终止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()的替代方法,以便从主进程中删除批处理作业?

谢谢 !!

最佳答案
subprocess模块是在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
commands

所以…如果您使用的是Python 2.4,则子进程是os.system的替代品

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

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...