Popen.stdout.readline()在Python 3.2中有效,但在Python 3.6中返回空字符串。

5
我正在使用Popen在ssh上启动一个telnet进程,通过telnet发送命令并检查输出以监视telnet的状态。奇怪的是,我发现该代码在Python 3.2.3中运行正常,但在没有代码更改的情况下在Python 3.6.5中无法获取输出。
我尝试过:
- 刷新stdout - 在stdout.write后等待最多10秒 - 检查了stderr
def nonblockingread(sout):
   fd = output.fileno()
   fl = fcntl.fcntl(fd, fcntl.F_GETFL)
   try:
       return sout.read()
   except:
       return ""

process = Popen(shlex.split("ssh anon@server \"telnet 0 2323\""), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(nonblockingread(process.stdout)) # works for both versions
process.stdin.write(b"start service 4\n")
print(nonblockingread(process.stdout)) # works in 3.2 but not 3.6 (prints empty line)
print(process.stdout.readline()) # also prints empty line in 3.6

为什么你要写入可读的 process.stdout 而不是可写的 process.stdin? - Dan D.
那是一个打字错误。 - Belos
似乎有一些代码丢失了 - 您从未设置任何非阻塞内容。例如,您的“服务4”是否实际启动? - Davis Herring
1个回答

2
默认情况下,3.2.4 和 3.3.1 中打开了缓冲区,在 Python 3 中意外关闭。 您需要刷新您的写入以便对方能够看到任何东西。请将其写入process.stdin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接