首页 > 解决方案 > 如果失败,如何退出python子进程

问题描述

我正在使用 SSH bash( command) 读取远程服务器的一些输出。我需要不断地这样做,所以我产生了子进程。它工作正常,除非服务器服务器在短时间内变得不可用。如果失败,如何重新启动 SSH 命令(整个子进程)?

我有以下代码:

(...)

process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
while True:
    line = process.stdout.readline()
    if lines == "" and process.poll() is not None:
        break
(...)

我认为这process.poll() is not None应该可以解决问题,但它似乎坚持下去

1000     21431  0.0  0.0      0     0 pts/0    Z+   Oct22   0:00 [ssh] <defunct>

并且不脱离while True:

标签: python-3.xsubprocess

解决方案


我的代码中有愚蠢的拼写错误,if lines == "" and process.poll() is not None:无法正确执行。另一件事是 ssh_config,设置值以断开@60 秒/1 次尝试是明智的。并避免 process.communicate() 因为它阻塞了整个线程。


推荐阅读