gpt4 book ai didi

python子进程没有终止

转载 作者:行者123 更新时间:2023-12-05 06:38:15 24 4
gpt4 key购买 nike

为了对一组文件执行各种工具,我使用以下命令类来调用它们。

import subprocess
import threading
import logging
logger = logging.getLogger('root')


class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None

def run(self, timeout, logfile):
def target():
logger.info('Thread started')
logger.info('Command: %s' % self.cmd)
if logfile is None:
self.process = subprocess.Popen(self.cmd, shell=True)
else:
logger.info('logging to file %s' % logfile.name)
self.process = subprocess.Popen(self.cmd, shell=True, stdout=logfile)
self.process.communicate()
logger.info('Thread finished')
self.process.kill()
thread = threading.Thread(target=target)
# make it a daemon
thread.daemon = True
thread.start()
thread.join(timeout)
if thread.is_alive():
logger.warn('Terminating process')
thread.join()
self.process.kill()
logger.info('Thread Returncode: %d' % self.process.returncode)
return self.process.returncode

我面临的问题是:

  • 我运行的工具/命令没有正确终止,尤其是当 python 程序运行很长时间(3 小时以上)时。

最佳答案

问题是您正在使用 shell=True 打开进程

self.process = subprocess.Popen(self.cmd, shell=True, stdout=logfile)

此处的解决方案:How to terminate a python subprocess launched with shell=True

关于python子进程没有终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46483886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com