开发者

Python strange behavior when called by Popen & writing to stdin

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, indee开发者_如何学JAVAd 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 from sys.stdin (like raw_input()) and then evaluates it as Python code. It's generally a bad idea to use input() in Python 2.x :) In Python 3.x, input() was removed and raw_input() was renamed to input(), 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 python command is probably (hopefully!) still the system-installed Python 2.x. Try running it with python3 or python3.1 instead.


Make sure that you're actually running Python 3? That looks suspiciously like the Python 2.x input() behavior, where it would interpret the input as Python expressions (as opposed to raw_input() which became Python 3's input()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜