简体   繁体   English

如何避免 Python 挂在 subprocess.run() 上

[英]How can I avoid Python hanging on subprocess.run()

I am creating a small automation script to interact with a game.我正在创建一个小的自动化脚本来与游戏进行交互。 The game is very vulnerable to crashing, but in an unpredictable way (after 30 minutes to 3 hours, depending on what happens in game).游戏很容易崩溃,但以不可预测的方式(30 分钟到 3 小时后,取决于游戏中发生的情况)。 Because of this, I wrote a small script below that was IDEALLY going to kill the program, kill the crash monitoring client that checks for crashes and offers to restart, and then relaunch the game and resume.正因为如此,我在下面写了一个小脚本,它是理想的终止程序,终止检查崩溃并提供重新启动的崩溃监控客户端,然后重新启动游戏并继续。 The issue is that I never reach past subprocess.run()问题是我从来没有达到过 subprocess.run()

it launches the game again, but it does not allow for any code after that to run.它再次启动游戏,但不允许在此之后运行任何代码。

import psutil
import time
import subprocess

def main():
    '''Process kill function'''    
    for proc in psutil.process_iter():
        # check whether the process name matches
        # print(proc.name())
        if any(procstr in proc.name() for procstr in\
            ['GameName.exe']):
            print(f'Killing {proc.name()}')
            proc.kill()
            time.sleep(5)
    for proc in psutil.process_iter():
        # check whether the process name matches
        # print(proc.name())
        if any(procstr in proc.name() for procstr in\
            ['GameCrashMonitor.exe']):
            print(f'Killing {proc.name()}')
            proc.kill()
    time.sleep(10)
    subprocess.run(r'PathToGame.exe')
    print(time.time())

if __name__ == "__main__":
    main()

This program successfully gets to subprocess.call, launches the game again, and then python hangs.这个程序成功进入subprocess.call,再次启动游戏,然后python就挂了。 I cant control c on ipython to stop it.我无法控制 ipython 上的 c 来阻止它。 I use Spyder and it even makes the icon for spyder on my task bar error and disappear.我使用 Spyder,它甚至使我的任务栏上的 spyder 图标出错并消失。

Try replacing subprocess.run() with variable = subprocess.Popen([r'PathToGame.exe']) https://docs.python.org/3/library/subprocess.html says that subprocess.run() waits for the command to complete, then returns a CompletedProcess instance.尝试更换subprocess.run()variable = subprocess.Popen([r'PathToGame.exe']) https://docs.python.org/3/library/subprocess.html说subprocess.run()等待命令完成,然后返回一个 CompletedProcess 实例。 Your command isnt completing.你的命令没有完成。 Furthermore, there is a timeout argument you could pass into run() but by default, it is None , and does not time out, if you wanted to still use .run()此外,您可以将超时参数传递给 run() 但默认情况下,它是None ,并且不会超时,如果您仍想使用.run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM