将python循环创建为“分离的”子进程

2024-05-08 19:27:21 发布

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

我有一个潜在的无限python“while”循环,即使在主脚本/进程执行完成之后,我也希望它继续运行。此外,如果需要的话,我希望以后能够从unix CLI中终止这个循环(即kill-SIGTERM PID),因此也需要循环的PID。我该如何做到这一点?谢谢!你知道吗

回路:

args = 'ping -c 1 1.2.3.4'

while True:
    time.sleep(60)
    return_code = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
    if return_code == 0:
        break

Tags: 脚本trueclireturn进程unixargscode
2条回答

Popen返回具有pid的对象。根据doc

Popen.pid The process ID of the child process.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

您需要关闭shell=True来获取进程的pid,否则它会给出shell的pid。你知道吗

args = 'ping -c 1 1.2.3.4'

while True:
    time.sleep(60)
    with subprocess.Popen(args, shell=False, stdout=subprocess.PIPE) as proc:
        print('PID: {}'.format(proc.pid))
        ...

在python中,父进程试图在退出时杀死所有的守护子进程。但是,您可以使用os.fork()创建一个全新的进程:

import os

pid = os.fork()
if pid:
   #parent
   print("Parent!")
else:
   #child
   print("Child!")

相关问题 更多 >