Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Interactive Interpreter always returns "Invalid syntax" on Windows

Tags:

python

windows

I've encountered an extremely confusing problem. Whatever I type into the Python interpreter returns "Invalid Syntax". See examples below. I've tried fooling around with the code page of the prompt I run the interpreter from, but it doesn't seem to help at all.

Furthermore, I haven't been able to find this particular, weird bug elsewhere online.

Any assistance anyone could provide would be lovely. I've already tried reinstalling Python, but I didn't have any luck - the problem is also there in both 3.13 and 2.7.

Running: Python version 3.1.3, Windows XP SP3.

Getting:

C:\Program Files\Python31>.\python
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.  
>>> 2+2
  File "<stdin>", line 1  
    2+2
       ^     
SyntaxError: invalid syntax

>>> x = "Oh, fiddlesticks."  
  File "<stdin>", line 1  
    x = "Oh, fiddlesticks."  
                           ^  
SyntaxError: invalid syntax
like image 316
user559217 Avatar asked Dec 31 '10 11:12

user559217


2 Answers

There is a known problem when running Python interactively and unbuffered, which is scheduled for fixing in 3.2 - and may be backported to older versions, see http://bugs.python.org/issue11098

The nasty thing is, one may be using unbuffered I/O without realising it. In my case (Python 2.5.4 (r254:67916)), I had some time ago set an environment variable such that Python would always run unbuffered (on Windows, this is PYTHONUNBUFFERED=YES, or whatever non-empty string substituted for YES) and then forgot about it. Removing the env.var. solved the problem for me.

So it may be worthwhile checking for this environment variable. It's not set by default.

like image 93
Paul B Avatar answered Sep 21 '22 15:09

Paul B


Now that the sample has been cleaned up it appears the problem is with the line termination.

This isn't a solution, but what happens if you create a file t.py containing this code, run it, and then type in some text?:

import sys; print(repr(sys.stdin.readline()))

If you type something like 2+2 then with luck this will show you what the Python interpreter is getting in your example and that in turn might give some clue to the problem.

You can also try this at the command prompt:

python -c "import sys; print(repr(sys.stdin.readline()))"

This will allow you to type one line and display the details of that one line.

like image 29
Duncan Avatar answered Sep 19 '22 15:09

Duncan