Python script only works with python command

On Linux (Ubuntu 11.04), for some reason, a Python script (specifically Django manage.py, but I don't think it matters) recently started acting weird:

When starting as

python manage.py 

it works just fine; however, with

 ./manage.py 

The following error is displayed:

 : No such file or directory 

File Permissions: 766. Any ideas?

-one
python linux shell
source share
5 answers

Glenn jackman's answer is correct, but I don’t have enough “reputation” to promote it, so I will post here. Your script is in Windows format, in which each line ends with a carriage return and line feed, and not just a line feed line. Many programs, including python, can handle any format without any problems. But when you run the script, the shell considers the carriage return to be part of the command name. Instead of running "/ usr / bin / env python", your shell tries to run "/ usr / bin / env python ^ M" (where ^ M is the line feed). You can say that this is because of the error message it gives you. Before “There is no such file or directory,” he prints the name of the program he was trying to execute. He also printed a translation line, which returned the cursor to the leftmost position in the line, which deleted everything before the colon.

If you do not have dos2unix, you can delete the lines with

 tr -d '\r' < manage.py > manage2.py; mv manage2.py manage.py 

You cannot read and write to the same file at the same time, so you should use a temporary file to store tr output.

+3
source share

Your file has a carriage return. Do you write it in a Windows text editor?

Try running dos2unix manage.py manage.py

+6
source share

I suspect that the shebang at the top of the file is incorrect. The file should begin with:

 #!/usr/bin/python 

(where the python path is the result of which python )

or

 #!/usr/bin/env python 
+2
source share

If the permissions are 766 and you are not the owner, you do not have permission to execute it. 6 means you can read and write, but not execute. Unusual for a system file that can be written in the world; usually it will be 755 . If you have root authority, use chmod 755 manage.py to fix it.

+1
source share

When starting the script directly, the script is launched with the interpreter specified in the first line:

 #!COMMAND 

Where COMMAND is / bin / bash for shell scripts. For python it is best to use

 #!/usr/bin/env python 

So, the python version is selected from the environment.

0
source share

All Articles