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

2024-04-26 21:56:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Linux中有一个创建ssh密钥的工作脚本。在macOS中,它挂起在wait()上

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)
child.wait()

Tags: import脚本childhostoslinuxsysenviron
1条回答
网友
1楼 · 发布于 2024-04-26 21:56:57

最后,我发现了问题所在。看起来ssh-keygen二进制文件略有不同,它会在之后输出一些东西

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

这将不会从子级读取任何数据,因此如果子级有未读的输出并已终止,这将永远阻止。换句话说,子级可能已打印输出,然后称为exit(),但在父级读取其输出之前,子级在技术上仍然处于活动状态

.wait()docs here

要解决此问题,read_非阻塞从子应用程序读取最多大小的字符。如果有可立即读取的字节,则将读取所有这些字节(直到缓冲区大小)

.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()

相关问题 更多 >