pythonbashterminalshebang

Syntax error on bash for running python script


I want run this simple python code int terminal:

#! /usr/bin/env python3

print('Hello world')

I saved this script as hello.py

I go to terminal to write down:

$ chmod +x hello.py

then I click enter. This is to allow permission to be granted. Terminal then showed me this:

-bash: $: command not found

Ok...I then write down the path to hello.py:

$ /Users/myname/Documents/MyPythonScripts/hello.py

I press enter. I was expecting terminal to print out hello world but to my horror, terminal show this:

/Users/myname/Documents/MyPythonScript/hello.py: line 3: syntax error near unexpected token `'Hello world''
/Users/hadi/Documents/MyPythonScript/hello.py: line 3: `print('Hello world')'

What's wrong here?

Btw, Running on macOS 10.13.3 and Python 3.6.3


Solution

  • First of all, this line:

    -bash: $: command not found
    

    tells that you've executed the "$" which is not right.

    Your command to set permissions should look like this:

    chmod +x hello.py
    

    Another comment is that the shebang line should be without space:

    #!/usr/bin/env python3