Python: Running a program - Should be simple

  • Context: Python 
  • Thread starter Thread starter Saladsamurai
  • Start date Start date
  • Tags Tags
    Program Python Running
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
Saladsamurai
Messages
3,009
Reaction score
7
Hello :smile:

As strange thing is happening. I have created a simple file using emacs (on a Mac) that contains the following:

Code:
def main():

    print "hello!"

if __name__ == "__main__":
    main()

And I have saved it in the working directory as hello.py

In a terminal window, if I type
Code:
python hello.py

it works great. Now I set the execute bit using
Code:
chmod +x hello.py

and when I try to run it using ./hello.py I get syntax errors?!

Code:
Python_Projects saladsamurai$ ./hello.py
./hello.py: line 1: syntax error near unexpected token `('
./hello.py: line 1: `def main():'

Any ideas on this? Thanks!
 
Physics news on Phys.org
Perhaps without #!/usr/bin/python it is treated as a bash script? Just guessing.
 
Borek said:
Perhaps without #!/usr/bin/python it is treated as a bash script? Just guessing.

Borek! Thanks! That what exactly it! I am not too good at terminal or Python. I saw the #!/usr/bin/python in the example file and I thought it was a comment :redface:
 
Saladsamurai said:
Borek! Thanks! That what exactly it! I am not too good at terminal or Python. I saw the #!/usr/bin/python in the example file and I thought it was a comment :redface:

It is a python comment. I think it would even be a shell script comment if it were anywhere but the first line.

But your shell treats the first line specially if it starts with #!, and interprets it as a path to something to execute to interpret the script.

This is why scripting languages all use # to start comments: so that this convention your shell uses can be used without confusing your scripting language.