我正在使用Popen通过ssh启动telnet进程,通过telnet发送命令并检查进程以监视telnet的状态。我遇到的奇怪的事情是代码在Python 3.2.3中运行良好但是当我在Python 3.6.5中运行它而没有代码更改时,它无法获得输出。
我试过了
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 and 3.3.1中默认启用缓冲,在Python 3中无意中关闭了。你需要flush
你的write
到process.stdin
让对方看到任何东西。