Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python syntax error in script, fine in REPL [duplicate]

When I put this python code into the REPL for python (the interactive shell), it works as expected:

>>> def get_header():
...     return (None,None,None)
... 
>>> get_header()
(None, None, None)

Note that the return statement is indented by four spaces, and I have checked to ensure there are no extraneous spaces.

when I put the exact same code into a python script file and execute it, I get the following error:

./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def get_header():'

WHY?

EDIT: this is the exact contents of test.py, white spaces and all:

def get_header():
    return (None,None,None)

get_header()

I have verified that the above script (test.py) does yield the above error as it above stands.

like image 774
djhaskin987 Avatar asked Sep 23 '26 10:09

djhaskin987


1 Answers

The reason this is not working is that you don’t have anything telling bash that this is a Python script, so it tries to execute it as a shell script, then throws an error when the syntax isn’t right.

What you need is to start the file with a shebang line, telling it what it should be run with. So your file becomes:

#!/usr/bin/env python

def get_header():
    return (None, None, None)

print get_header()
like image 58
dhwthompson Avatar answered Sep 25 '26 23:09

dhwthompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!