期望:无法写信给STDIN-为什么?

问题描述

为什么不起作用?

data,status = run('grep o',stdout=True,stdin='lol')
print(f'data: {data},status: {status}')

完整代码:

import pexpect
import sys
def run(cmd,prompts=[],password=None,stdout=False,stdin=''):
    """runs and interacts with external commands"""
    child = pexpect.spawn(cmd,encoding='utf-8')
    for prompt in prompts:
        try:
            child.expect(prompt)
        except pexpect.exceptions.TIMEOUT:
            print(f'prompt "{prompt}" not matched')
            sys.exit(1)
        child.sendline(password)
    child.send(stdin)
    try:
        data = child.read() if stdout else None
    except pexpect.exceptions.TIMEOUT:
        print('command took too long to print to stdout')
        sys.exit(1)
    child.close()
    return data,child.exitstatus

data,status: {status}')

解决方法

这有效:

def run(cmd,prompts=[],password=None,stdout=False,stdin=None):
    """runs and interacts with external commands"""
    child = pexpect.spawn(cmd,encoding='utf-8')
    for prompt in prompts:
        try:
            child.expect_exact(prompt)
        except pexpect.exceptions.TIMEOUT:
            err(f'prompt "{prompt}" not matched')
        child.sendline(password)
    if stdin is not None:
        child.sendline(stdin)
        child.sendeof()
        child.sendeof()
    try:
        data = child.read() if stdout else None
    except pexpect.exceptions.TIMEOUT:
        err('command took too long to print to stdout')
    exitstatus = child.wait()
    return data,exitstatus

差异:

  • child.send(stdin)-> child.sendline(stdin)
  • child.sendeof()重复两次。这不是必需的 特定示例(即运行grep o),但显然对于 scrypt enc - out.enc。我不知道为什么。

我不知道为什么以上任何方法都能奏效。如果您知道,请告诉我。

没关系,但是我使用的是函数err而不是printsys.exit

def err(msg):
    sys.stderr.write('{ERR}*{CLR} {}\n'.format(msg,**THEME))
    sys.stderr.flush()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...