user380772
user380772

Reputation:

input working in shell but not terminal

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?

Upvotes: 0

Views: 3830

Answers (3)

Syed Zaidi
Syed Zaidi

Reputation: 41

You need to run like

python3 /users/rickyd/desktop/test.py

it should work

Upvotes: 4

John Gaines Jr.
John Gaines Jr.

Reputation: 11544

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).

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172309

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?

Upvotes: 3

Related Questions