python-3.x - 执行 popen 并超时

标签 python-3.x multiprocessing subprocess

所以我尝试通过 subprocess.popen() 专门执行 Linux 命令。我只想等待 30 秒来执行此命令,因为在某些情况下我的命令会挂起并且程序将永远等待。 以下是我使用的两种方法。

方法1

cmd = "google-chrome  --headless  --timeout=30000  --ignore-certificate-errors --print-to-pdf out.pdf https://www.google.com/
process = subprocess.call(cmd, shell=True)
process.wait() # Here I want to wait only till 30 secs and not untill process completes

方法2

from multiprocessing import Process
p1 = Process(target=subprocess.call, args=(cmd,))
        processTimeout = 50
        p1.start()
        p1.join(processTimeout)
        if p1.is_alive():
            p1.terminate()

在第二种方法中,文件甚至没有被创建。请提出一个选项。

最佳答案

Popen.wait采用可选的timeout 参数。您可以使用它来仅等待特定时间的完成。如果超时触发,您可以终止该进程。

process = subprocess.call(cmd)
try:
    # if this returns, the process completed
    process.wait(timeout=30)
except subprocess.TimeoutExpired:
    process.terminate()

从 Python 3.5 开始,您还可以使用 subprocess.run便利功能。

subprocess.run(cmd, timeout=30)

请注意,这仍然会引发 TimeoutExpired 但会自动终止子进程。

关于python-3.x - 执行 popen 并超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52109038/

相关文章:

python - Python 3.2 是否有 PyMongo 的等价物?

python - 如何在 Python 多处理中动态创建每个进程队列

python - 控制python代码在不同的核心上运行

python - 无法修改函数以独立工作而不是依赖于返回的结果

scala - 在 Scala 中将外部命令作为子进程调用

python - 以附加模式将子进程输出转储到文件中

Python 避免孤儿进程

Python 3 : Multiprocessing API calls with exit condition

python - 如何使用 strip() 从句子中删除\n 字符

python - pyenv 安装多个 python,但只识别一些