Belos
Belos

Reputation: 291

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. 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.

I have tried

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

Upvotes: 5

Views: 1442

Answers (1)

Davis Herring
Davis Herring

Reputation: 40013

Buffering was turned on by default in 3.2.4 and 3.3.1, having been turned off inadvertently in Python 3. You need to flush your write to process.stdin for the other side to see anything.

Upvotes: 2

Related Questions