gpt4 book ai didi

java - 如何在Python中使正在运行的jar程序超时

转载 作者:行者123 更新时间:2023-12-01 12:49:14 25 4
gpt4 key购买 nike

我正在使用以下 Command 类来使正在运行的命令超时。它与 shell 命令一起工作得很好,但是当我使用命令 java -jar 将其传递给 Command 类来启动 java 程序时,它似乎没有终止 java 进程。请帮忙。

class Command(object):

cmd = None
process = None
status = None
output, error = '', ''

def __init__(self, cmd):
# if isinstance(cmd, basestring):
# cmd = shlex.split(cmd)
self.cmd = cmd
#self.process = None

def run(self, timeout, outputfile, errfile):
def target():
print 'Thread started'
try:
print self.cmd
open(outputfile, 'w').close()
open(errfile, 'w').close()
self.process = subprocess.Popen(self.cmd, shell=True, stdout = file(outputfile, 'w+'), stderr = file(errfile, 'w+')) #
(self.output, self.error) = self.process.communicate() #
self.status = self.process.returncode
print self.output #"Out:'%s'" %
print self.error #"Err:'%s'" %
print 'Thread finished'
except:
self.error = traceback.format_exc()
self.status = -1
print self.error

thread = threading.Thread(target=target)
thread.start()

thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.kill() #terminate
thread.join()
print self.status

最佳答案

这是因为 shell 为 java 启动了一个子进程。您可以删除 shell=True 或使用命令 exec java -jar ...

来自 exec 的手册页:

The exec() family of functions replaces the current process image with a new process image.

关于java - 如何在Python中使正在运行的jar程序超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24377187/

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