subprocess.run 超时失败的解决方法?

Workaround for timeout failure on subprocess.run?

是否有 https://bugs.python.org/issue37424 的解决方法?

那个虫子咬我。我在 Raspberry Pi OS 上,当我安装 sudo apt install python3.

时得到了 Python 3.7.3

不幸的是,该错误仅在 Python 3.7.5 及更高版本中得到修复。

我只是需要暂停工作。

FWIW,这是我的代码:

def command(string, verbose=None, echo_commands=ECHO_COMMANDS, timeout=SHORT_TIMEOUT):
    ''' Executes string as a command by the OS.
        Returns subprocess.CompletedProcess (stout, stderr, returncode, etc.).

        Note usual security precautions since shell=True (DO NOT use this with user input).
    '''

    if verbose is None:
        verbose = VERBOSE

    while True:
        try:
            if echo_commands:
                print("command:", string)

            cp = subprocess.run(string, shell=True, capture_output=True, text=True, timeout=timeout)

            if verbose:
                print(cp.stderr, cp.stdout)

            return cp

        except Exception as e:
            print(e)
            reboot_camera() #...and try again

我找到了一个解决方案 - 使用 shell=False(然后超时有效)并使用 shlex.split 将命令解析为 Python 中的参数,而不是要求 shell做吧。所以:

string = shlex.split(string) # workaround for https://bugs.python.org/issue37424 (plus shell=False instead of True)

cp = subprocess.run(string, shell=False, capture_output=True, text=True, timeout=timeout)

为了使其也适用于 Windows,我不得不修改包含可执行文件名称的字符串以包含完整路径(似乎 Windows 不搜索 $没有 shell==True).

的路径

旧:CHDKPTP_EXE = r'chdkptp'

新:CHDKPTP_EXE = r'c:\bin\chdkptp.bat'