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

时间:2019-04-24 21:54:55

标签: python python-3.6 python-3.2

我正在使用Popen通过ssh启动telnet进程,通过telnet发送命令,并检查进程的输出以监视telnet的状态。我遇到的奇怪的事情是该代码在Python 3.2.3上运行正常,但是当我在Python 3.6.5中运行且未更改代码时,它无法获取输出。

我尝试过

  • 刷新标准输出

  • 在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

1 个答案:

答案 0 :(得分:2)

默认情况下,3.2.4 and 3.3.1中的缓冲已打开,而在Python 3中无意中将其关闭。您需要flush write 设置为{{1 }},让对方看不到任何东西。