简体   繁体   English

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

[英]Popen.stdout.readline() works in Python 3.2 but returns empty string in Python 3.6

I am using Popen to start a telnet process over ssh, send commands through the telnet and check the process for output to monitor the state of the telnet. 我正在使用Popen通过ssh启动telnet进程,通过telnet发送命令并检查进程以监视telnet的状态。 The weird thing I encountered is that the code works fine with Python 3.2.3 but when I run it in Python 3.6.5 with no code changes, it fails to get the output. 我遇到的奇怪的事情是代码在Python 3.2.3中运行良好但是当我在Python 3.6.5中运行它而没有代码更改时,它无法获得输出。

I have tried 我试过了

  • flushing the stdout 冲洗stdout

  • waiting up to 10s after stdout.write 在stdout.write之后等待10秒

  • checked stderr 检查过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

默认情况下,在3.2.4和3.3.1中打开了缓冲,在Python 3中无意中关闭了。您需要将write flushprocess.stdin ,以便另一方看到任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM