Ubuntu Python shebang line not working

If you are trying to run the command as

$ test.py

the error may not have anything to do with the shebang. Rather, the directory that test.py resides in is not in your PATH. Try

$ ./test.py

to bypass PATH lookup.

(This is in addition to making sure that the script itself is executable.)


On the python docs page it says:

To easily use Python scripts on Unix, you need to make them executable, e.g. with

$ chmod +x script and put an appropriate Shebang line at the top of the script. A good choice is usually

#!/usr/bin/env python which searches for the Python interpreter in the whole PATH. However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python as the interpreter path.

I don't know if this applies for you or not.


Apart from executing the script with a preceding dot or making it executable, there might be another issue:

If you try to use a script written with a windows editor, it may contain windows line endings. Removing these can make the shebang work again.

To remove such line endings, refer to How to convert Windows end of line in Unix end of line (CR/LF to LF) for instance.

See also my general remarks on failed shebang evaluations at my other answer.