Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to call a python script script.py from the terminal by simply typing script. Is this possible? If so, how?

I know I can avoid typing python script.py by adding #!/usr/bin/env python to the top of the script, but I still have to add the suffix .py in order to run the script.

share|improve this question

3 Answers 3

up vote 8 down vote accepted

Unix/Linux file systems do not rely on extensions the way windows does. You should not need the .py at the end of a file to run it.

You can run the file by either calling it with the interpreter:

python ScriptFile

Or by marking it executable and defining the interpreter on the first line (e.g. #!/usr/bin/python).

If you are unable to execute the file with:

/Path/to/ScriptFile

check the permissions with

ls -l ScriptFile

You may need to add the executable flag and chmod it so it will execute for you.

If you are using custom scripts regularly you may want to make sure the directory you store them is added to the PATH environment variable.

share|improve this answer
    
The file is in ~/workspace/python. I've added ~/workspace/python to my path, I ran sudo chmod a+x script.py", and I've added the shebang line (#!/usr/bin/env python) to the top of the script. I can run the script by typing *script.py, but just typing script doesn't work. –  jmau5 Dec 28 '11 at 7:03
    
In unix/linux everything is a file and responds to its file name. You can not call Script.py as script. Try renaming the file from script.py to script and it should fix your issue. –  Patrick Dec 28 '11 at 7:15
    
Sorry, I misunderstood! Everything solved, thanks! –  jmau5 Dec 28 '11 at 7:54

The .py extension is unnecessary for running the script. You only have to make the script executable (e.g. by running chmod a+x script) and add the shebang line (#!/usr/bin/env python).

share|improve this answer
    
See my comment on Patrick's reply. –  jmau5 Dec 28 '11 at 7:04

As an option you could create wrapper for your script (a .py file):

For example, you have a script runme.py so you can create new file runme to wrap the script:

#!/usr/bin/env python
import runme

and then call the runme.py functionality just by invoking runme in the shell.

That is useful for multiplatform scripts, cause on Windows platform you can assign .py files to be invoked just by name without extension and shebang in the header, but on the linux platform you can't and thus the wrapper comes out.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.