【问题标题】:Python code terminates while trying to run an exe file using subprocess.PopenPython 代码在尝试使用 subprocess.Popen 运行 exe 文件时终止
【发布时间】:2020-07-12 03:11:24
【问题描述】:

我正在尝试运行这个 exe:

s = subprocess.Popen('make.exe -console -verbose', stderr=subprocess.PIPE, stdin=subprocess.PIPE)

虽然我可以在这里使用 subprocess.run,但我需要在“解锁”模式下运行它,因为我还有其他部分代码要同时执行。

(PS:subprocess.run 可以正常工作,但在这种情况下,其余代码不会进一步移动)

【问题讨论】:

    标签: python subprocess pipe executable popen


    【解决方案1】:

    对 Popen 的调用是“非阻塞的”。换句话说,子进程被创建,Popen 立即返回。如果你想对子进程做一些事情(比如读取输出或者只是等待它完成),那么你可以使用来自docs 的方法调用之一,比如wait() 或communicate()。

    如果您愿意等待子进程结束,请使用带有可选超时值的 wait():

    # create the sub process
    s = subprocess.Popen('make.exe -console -verbose', stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    
    for _ in range(6):
        try:
            # wait for 10 seconds
            s.wait(10)
        except TimeoutExpired:
            print("Waited 10 seconds, process still not done")
            continue
    
    print("Tired of waiting")
    s.kill()
    

    【讨论】:

    • 我在这里使用的 .exe 文件必须在后台连续运行。但是对于 Popen,它一开始就会终止。
    • 那么不要提供等待的号码。如果你调用s.wait(),那么它将无限期阻塞(直到 make.exe 被终止)。
    • 是的,我没有调用 s.wait()。但问题是调用 subprocess.Popen() 时 exe 文件被终止。此外,当我使用 subProcess.run() 时,exe 运行得非常好。但是 subprocessrun() 不能用于“非阻塞”。
    猜你喜欢
    • 2014-06-06
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2022-10-05
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多