我想知道当异步进程超时完成时是否有办法恢复返回码。 限制是我想在另一个 python 文件中的另一个类中恢复此代码。另外,我不想阻止我的 GUI ...
在我的 MainView.py 中,我的代码如下:
if self.comboBox.currentText() == "HASHCAT" :
self.process = Hashcat(MainWindow.hashcatPath, 100, 3, MainWindow.hashFilePath, MainWindow.dictPath, MainWindow.pathOutFile)
self.process.run(2)
我的 Hashcat.py 文件如下所示:
def run(self,timeout):
def target():
FNULL = open(os.devnull, 'w')
if self.typeAttack == 0 :
self.subprocess=\
subprocess.Popen([self.pathHashcat,"-m",str(self.algoHash),"-a",str(self.typeAttack),self.pathHashFile,self.pathDict,
"-o",self.pathOutFile],
stdout=FNULL, stderr=subprocess.STDOUT)
if self.typeAttack == 3 :
self.subprocess =\
subprocess.Popen(
[self.pathHashcat, "-m", str(self.algoHash), "-a", str(self.typeAttack),self.pathHashFile,"-o",self.pathOutFile])
self.timer.start()
self.subprocess.wait()
self.timer.cancel()
def timer_callback():
print('Terminating process (timed out)')
self.subprocess.terminate()
self.thread = threading.Thread(target=target)
self.timer = threading.Timer(timeout, timer_callback)
self.thread.start()
print(self.timer.isAlive)
最佳答案
调用terminate
只是发送信号来终止进程;您可能仍然需要wait
之前你可以得到 returncode
;否则,它仍然是None
。
但是,returncode
不太可能那么有意义。您刚刚使用 SIGTERM
终止了该进程,因此 returncode
将是 -SIGTERM
。
如果问题只是 terminate
花费的时间太长,或者不确定 - 那么,SIGTERM
应该是子进程可以用来干净关闭的东西,这可能需要时间,如果 child 有严重的错误,甚至可能什么也做不了。如果您确实希望它立即消失,则需要发送 SIGKILL
。 (这是终端中 kill 12345
和 kill -9 12345
之间的区别。)从 subprocess
执行此操作的方法是调用kill
方法而不是终止
。
理想的解决方案通常是双重超时,例如,在 X 秒后终止
,如果又过了 Y 秒而没有终止,则kill
。这使进程有机会尽可能正常关闭,但仍保证在 X+Y 秒后确定性终止。但这取决于某些程序的某些用途,给 child 额外的 Y 秒希望完成比给它 Y 秒的清理更重要。或者两种方式都没有太大区别,单步 kill
只是编码更简单。
(如果您使用的是 Windows,则情况会有所不同,但由于您使用的是 OS X,所以这无关紧要。)
关于python - 恢复超时完成的异步子进程返回代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340955/