Two (related?) questions here.
I was trying to write a program to start an external process, and then simultaniouly read from stdout and write to stdin. Everything seemed to be working, however the process was not responding to the data sent to its stdin pipe. Do you know why this would be?(1)
This second question is solved now.
I wrote two testing scripts, the first was as such:
# recv.py
while True:
print(input())
The second was designed to call the other using Popen, the give it some arbitrary input:
# send.py
recv = subprocess.Popen(["python", "recv.py"], stdin=subprocess.PIPE)
recv.stdin.write(b"Hello\n")
recv.stdin.write(b"World.\n")
This is what I got when I ran it:
skyler@pro:testing$ python send.py
skyler@pro:testing$ Traceback (most recent call last):
File "recv.py", line 30, in <module>
main()
File "recv.py", line 26, in main
print(input())
File "<string>", line 1, in <module>
NameError: name 'Hello' is not defined
It looks like for whatever reason the result of input() is being treated like part of the line, instead of a string, indeed when I set a variable Hello in recv.py, it printed the contents of Hello. Why is this happening?(2)
I’m running python 3.1.2 on Mac OSX.
What you’re seeing is the expected behaviour of Python 2.x’s
input()function, which takes a line fromsys.stdin(likeraw_input()) and then evaluates it as Python code. It’s generally a bad idea to useinput()in Python 2.x 🙂 In Python 3.x,input()was removed andraw_input()was renamed toinput(), which may be why you’re confused about what it does.You’re not executing Python 3.x, even though you may have it installed. The
pythoncommand is probably (hopefully!) still the system-installed Python 2.x. Try running it withpython3orpython3.1instead.