python 调用shell time命令_如何在Python中调用具有指定时间限制的系统命令?

在Python中创建调用系统命令的应用时,若命令执行超过预设时间(如10秒),应能终止这些命令。通过使用`subprocess`模块和多线程,结合`os.setsid()`和`os.killpg()`可以实现这一目标。当超时时,发送`SIGTERM`信号来结束进程组,防止后台进程遗留。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参见英文答案 > How to terminate a python subprocess launched with shell=True                                    10个

我正在创建一个调用一些系统命令的Python应用程序.但是,如果它们花费太多时间(比如10s),我希望它终止这些命令.我尝试使用一些子过程自己做这件事 – 没有太大的成功.在stackoverflow上搜索后,我发现了以下问题:

Using module ‘subprocess’ with timeout

它有一个答案,几乎对我有用 – 问题是,当进程被“终止”时,它实际上不是 – 实际上,即使我的脚本完成后,该进程仍然在后台运行.当然这不是一个理想的效果,但我找不到解决方法.有没有一个解决这个问题的优先解决方案?

来自上述答案的代码(不良代码)供参考:

import subprocess, threading

class Command(object):

def __init__(self, cmd):

self.cmd = cmd

self.process = None

def run(self, timeout):

def target():

print 'Thread started'

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

self.process.communicate()

print 'Thread finished'

thread = threading.Thread(target=target)

thread.start()

thread.join(timeout)

if thread.is_alive():

print 'Terminating process'

self.process.terminate()

thread.join()

print self.process.returncode

command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")

command.run(timeout=3)

command.run(timeout=1)

解决方法:

你可以在这里找到答案:

只需将preexec_fn = os.setsid添加到Popen命令即可

终止使用:

os.killpg(self.process.pid, signal.SIGTERM)

代替:

self.process.terminate()

别忘了导入os,信号

所以你会得到:

import subprocess, threading

import os,signal

class Command(object):

def __init__(self, cmd):

self.cmd = cmd

self.process = None

def run(self, timeout):

def target():

print 'Thread started'

self.process = subprocess.Popen(self.cmd, shell=True, preexec_fn=os.setsid)

self.process.communicate()

print 'Thread finished'

thread = threading.Thread(target=target)

thread.start()

thread.join(timeout)

if thread.is_alive():

print 'Terminating process'

os.killpg(self.process.pid, signal.SIGTERM)

thread.join()

print self.process.returncode

command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")

command.run(timeout=3)

command.run(timeout=1)

标签:python,multithreading

来源: https://codeday.me/bug/20190708/1402488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值