【问题标题】:How to avoid Python Subprocess stopping execution如何避免 Python 子进程停止执行
【发布时间】:2021-02-25 07:37:29
【问题描述】:

我有一个处理大量文件的 python 程序,一步是通过 .JAR 文件完成的 我目前有类似的东西

    for row in rows:
        try:
            subprocess.check_call(f'java -jar ffdec/ffdec.jar -export png "{out_dir}/" "{row[0]}.swf", stdout=subprocess.DEVNULL)
        except (OSError, subprocess.SubprocessError, subprocess.CalledProcessError):
            print(f"Error on {row[0]}")
            continue

这适用于执行 os 命令(我在 Windows 10 上)并且不会因错误而停止。 但是,有一个特定的错误会停止我的 python 程序的执行。 我认为这是因为 .jar 文件并没有真正停止,并且仍然在后台运行,从而阻止了 python 继续。

我有办法在 Python 中调用命令并异步运行它,还是在 20 秒超时后跳过它? 我也可以制作一个 Java 程序来运行该部分的过程,但为了方便起见,我更喜欢全部都在 Python 上

为了以防万一,我将把停止我的程序的错误放在这里(所有其他错误都被 try: 正确捕获:)

f�vr. 25, 2021 8:05:00 AM com.jpexs.decompiler.flash.console.ConsoleAbortRetryIgnoreHandler handle
GRAVE: Error occured
java.util.EmptyStackException
    at java.util.Stack.peek(Unknown Source)
    at com.jpexs.decompiler.flash.exporters.commonshape.SVGExporter.addUse(SVGExporter.java:230)
    at com.jpexs.decompiler.flash.timeline.Timeline.toSVG(Timeline.java:1043)
    at com.jpexs.decompiler.flash.exporters.FrameExporter.lambda$exportFrames$0(FrameExporter.java:216)
    at com.jpexs.decompiler.flash.RetryTask.run(RetryTask.java:41)
    at com.jpexs.decompiler.flash.exporters.FrameExporter.exportFrames(FrameExporter.java:220)
    at com.jpexs.decompiler.flash.console.CommandLineArgumentParser.parseExport(CommandLineArgumentParser.java:2298)
    at com.jpexs.decompiler.flash.console.CommandLineArgumentParser.parseArguments(CommandLineArgumentParser.java:891)
    at com.jpexs.decompiler.flash.gui.Main.main(Main.java:1972)

【问题讨论】:

  • 是的。据我所知,check_call() 等待进程结束,而Popen() 不会。我建议你调查一下。

标签: python jar os.system


【解决方案1】:

深入查看子流程文档后,发现了一个叫超时的参数:

subprocess.check_call('...', stdout=subprocess.DEVNULL, timeout=20)

这可以为我完成这项工作

Documentation for timeout

【讨论】:

    最近更新 更多