0

I have:

filename = input()
with open(filename) as file:
    print('It opened.')

saved on my desktop as "test.py".

I run it from the terminal, and get:

blahblahblah:~ rickyd$ python /users/rickyd/desktop/test.py
/users/rickyd/desktop/tryme.txt
Traceback (most recent call last):
  File "/users/rickyd/desktop/test.py", line 1, in <module>
    filename = input()
  File "<string>", line 1
    /users/rickyd/desktop/tryme.txt
    ^
SyntaxError: invalid syntax

When I run it in the shell, it works perfectly:

>>> ================================ RESTART ================================
>>> 
/users/rickyd/desktop/tryme.txt
It opened.
>>> 

Why isn't it working in the terminal?

Is there any way to make sure that (at least for code not explicitly designed to do otherwise) the shell and the terminal will give the same behavior, so I won't have to check both separately?

3 Answers 3

4

You need to run like

python3 /users/rickyd/desktop/test.py

it should work

Sign up to request clarification or add additional context in comments.

Comments

3

When you are running it in the terminal, you are running it with Python 2. That's why it doesn't work.

Which OS are you on, and how do you run it?

4 Comments

Well spotted, but you may need to explain the Great Renaming :)
I'm on Mac OS 10.6.5 . I'm not sure what you mean by how do I run it; I have IDLE 3.1.2 for the shell (same version of Python), and I run from terminal with "python "+[path of program]+return. I don't know how to get terminal to run v3. (Hopefully that part is why you're asking for more info.)
Maybe calling python3 will invoke python 3.x. Try pressing tab after typing python and analyzing completion variants.
@ricky: Python3 is run with python3. In general you should always make sure you know exactly what python you are running by giving the full path, like /usr/bin/python3 or /opt/python31/bin/python3 or something. See also: regebro.wordpress.com/2011/02/02/…
1

You can check the version of your command line Python by either typing:

C:\work>python -V
Python 2.7.1

(that's an upper case V) or just by typing python with no options and looking at the version number displayed at the start of the interactive prompt messages. This appears to be a 2.x vs. 3.x issue with the fact that input() in 3.x is equivalent to raw_input() in 2.x (in 2.x, the input() function reads in and evaluates the input as python code, which is why you get the "invalid syntax" error).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.