python脚本:pexpect挂在child.wait()上吗?

我在Linux中有一个工作脚本,可以创建ssh-key。在macOS中,它挂在wait()上。

const response = await fetch('http://example.com/jobs.json');
const options = await response.json();
for (let i = 0; i < options.length; i++) {
// etc.
liuxin067 回答:python脚本:pexpect挂在child.wait()上吗?

最后,我找到了问题。看来ssh-keygen二进制文件稍有不同,并且它在之后输出一些东西。

因为wait()是一个阻塞调用。

这不会从孩子那里读取任何数据,因此,如果孩子有未读的输出并终止了,则 这将永远阻塞 。换句话说,孩子可能已经打印了输出,然后称为exit(),但是,从技术上讲,孩子仍然活着,直到父级读取其输出。

.wait()docs here

为解决此问题,read_nonblocking从子应用程序中读取最大大小的字符。如果有立即读取的字节,则将读取所有这些字节(最大为缓冲区大小)。

.read_nonblocking()docs here

工作解决方案


import os
import sys

import pexpect


passphrase = os.environ['HOST_CA_KEY_PASSPHRASE']

command = 'ssh-keygen'
child = pexpect.spawn(command,args=sys.argv[1:])
child.expect('Enter passphrase:')
child.sendline(passphrase)

# Avoid Hang on macOS
# https://github.com/pytest-dev/pytest/issues/2022
while True:
    try:
        child.read_nonblocking()
    except Exception:
        break

if child.isalive():
    child.wait()
本文链接:https://www.f2er.com/3143857.html

大家都在问