简体   繁体   中英

Why does this code behave differently in Python3.1 than in Python2.6?

I'm very new to programming so I apologize in advance if my question is too silly.

#!/usr/bin/python2.6  
import subprocess, time  
p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)  
for i in 'abcd':  
    p.stdin.write(str.encode(i+'\n'))  
    output=p.stdout.readline()  
    print(output)  
    time.sleep(1)

Executing this code in Python 2.6 prints letters a, b, c, d , each line of output appears after a second. This is expected behavior. But in Python 3.1 execution is blocked at line output=p.stdout.readline() . How to correct this for Python 3.1?

Appears to be a difference in buffering. Adding a p.stdin.flush() call solved the problem. (See the comments above).

Community wiki as I deserve no credits for this answer, but some answer needs to be marked accepted.

[@Geo Pop: Please "accept" this question, as it apparently is correct.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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