Python:Popen 子进程 stdin=PIPE 自动发送换行符

问题描述

我正在遵循这个 S.O. 的解决方案。发帖:

A non-blocking read on a subprocess.PIPE in Python

我的目标不仅是在循环内对子进程进行非阻塞读取,而且还能够写入子进程以响应来自进程的提示在这个例子中,我试图自动执行来自 neo4j 的 cypher-shell 命令来设置用户凭据:

import subprocess
import os 
import time
import sys

p = subprocess.Popen('cypher-shell',stdin=subprocess.PIPE,stderr=subprocess.STDOUT,stdout=subprocess.PIPE)
os.set_blocking(p.stdout.fileno(),False)
start = time.time()
while True:
    # first iteration always produces empty byte string in non-blocking mode
    for i in range(2):    
        line = p.stdout.readline()
        print(i,line)
        time.sleep(0.5)    
    if time.time() > start + 5:
        break
p.terminate()

我希望第一个非空行是“用户名:”,但我得到“由于身份验证失败,客户端未经授权”,这表明进程以某种方式收到了来自标准输入的输入,它被解释为用户输入。如果我删除 stdin=subprocess.PIPE,我确实得到了“用户名”。所以不知何故 stdin=subprocess.PIPE 把事情搞砸了。我有什么误解?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)