0

I am running python 3.6 on Linux. When I use the python shell to test the code, it works as it is supposed to do. However, if run from the linux terminal, I get a name error.

#!/usr/bin/python
print("Hi")
name = input("What\'s your name?")
print (name, "is a cool name")

Then after inputting a name from the linux terminal, I get the following error:

Traceback (most recent call last):
  File "./test.py", line 3, in <module>
    name = input("What\'s your name?")
  File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined

I know that if run on python 2, you need to use raw input, however this is not used in python 3. Is there another line of code so that the linux terminal accepts it, like #!/usr?

hyde
  • 60,639
  • 21
  • 115
  • 176
  • 1
    how did you run it ? – BoilingFire Jun 27 '17 at 17:07
  • 1
    What does `/usr/bin/python --version` give you? – syntonym Jun 27 '17 at 17:07
  • try: `print '{} is a cool name'.format(name)` – EvgenyKolyakov Jun 27 '17 at 17:07
  • @syntonym Without it, the linux terminal does not accept it as python code. –  Jun 27 '17 at 17:08
  • 1
    No, i mean what happens if you type `/usr/bin/python --version` into your terminal. It looks like you are running python2, even if you don't intend to. – syntonym Jun 27 '17 at 17:09
  • to be sure you use python 3 type `python3 test.py` – BoilingFire Jun 27 '17 at 17:12
  • It sounds like `/usr/bin/python` is Python 2, not Python 3. How are you running the Python shell? – Barmar Jun 27 '17 at 17:33
  • @syntonym You're right, for some reason the linux terminal says I am using 2.7, but python says I am running 3.6.2rc1. What happened? –  Jun 27 '17 at 17:49
  • 1
    @matt-333: What happens is that you have both python2 and python3 installed. My guess is that python3 is first in the path so when you run `$ python ` you are running python3, but `/usr/bin/python` is actually python2. You can check where it is with `$ which python` or `$ type python`. – rodrigo Jun 27 '17 at 17:53
  • @matt-333 What do you mean with "python says I'm running 3.6"? How do you execute python if you do that? – syntonym Jun 27 '17 at 17:53
  • @syntonym I'm just reading off what it says in the header. –  Jun 27 '17 at 17:54

2 Answers2

1

With the shebang line #!/usr/bin/python you are telling the system to use Python 2.

In Python 2, you would need to change input to raw_input, as follows:

#!/usr/bin/python
print("Hi")
name = raw_input("What\'s your name?")
print(name, "is a cool name")

See Greeting program for more information.

However, to tell the system to run the script with Python 3, change your shebang line to #!/usr/bin/python3, or preferably #!/usr/bin/env python3.

Daniel Jonsson
  • 3,261
  • 5
  • 45
  • 66
0

You can run like this: python3 test.py

Rubel
  • 1,255
  • 14
  • 18