Here is a test.py file:
#!/usr/bin/python
print "hello"
a=raw_input()
print a
when use ./test.py to run this file,it will first print 'hello',and then ask me to input a ,and finally print a,there is nothing wrong,it works like that:
> hello
> 123
> 123
And of course it works correctly.
But when i want to use netcat to connect this py file,first i execute: socat tcp-l:9991,fork exec:python test.py
And then i use another shell in the local machine to connect the py file: nc 127.0.0.1 9991
Then the py file will first ask me to input a instead of printing 'hello',and after i input a,it will then print 'hello' and finally print a,it works like that:
> 123
> hello
> 123
And obviously it is a wrong execution sequence,so i wonder why this thing will happen? And what should i do to fix this problem and let it run with a correct sequence when i use nc to connect it.Thank you very much!
With print statement you are writing to the output stream, but you don't flush it immediately by default. Try something like this:
#!/usr/bin/python
import sys
print "hello"
sys.stdout.flush()
a=raw_input()
print a
sys.stdout.flush()
This will force it to display anything that is in stdout buffer.