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

问题描述 投票:5回答:1

我正在使用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
python python-3.6 python-3.2
1个回答
2
投票

3.2.4 and 3.3.1中默认启用缓冲,在Python 3中无意中关闭了。你需要flush你的writeprocess.stdin让对方看到任何东西。

© www.soinside.com 2019 - 2024. All rights reserved.