2

Whilst running python scripts from my linux terminal, I find myself typing in python myfile.py way too much. Is there a way on linux (or windows) to execute a python script by just entering in the name of the script, as is possible with bash/sh? like ./script.py?

3 Answers 3

3

At the top of the script, put

#!/usr/bin/python

or whatever the path to Python is on your computer (the result of which python on Linux). This tells the system to run your script using python. You'll also need to do chmod +x script.py for it to work.

Or if you're really lazy, use alias p=python or something.

Sign up to request clarification or add additional context in comments.

1 Comment

In Python, is often a better practice to use #!/usr/bin/env python to enable running using a virtualenv.
1

you will need to chmod 0755 script.py and as a first line in script have something like

#!/usr/bin/python

Comments

0

The first line of your Python script should be:

#!/usr/bin/env python

or

#!/usr/bin/env python3

Depending on your version, and if Python 3 is your default or not.


Then, set executable bits at the shell (maybe with sudo if needed):

chmod +x my_script_name.py

Note that with the above done, you could rename your Python script

mv my_script_name.py my_script_name

and then execute your Python script just by:

my_script_name

at the shell line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.