Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python script without the "python" keyword

How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files?

Right now I have to do this: python script.py

What I like to do is this: script.py

like image 218
Sindre Sorhus Avatar asked May 04 '11 07:05

Sindre Sorhus


People also ask

Can you run Python scripts without python?

py2exe is a Python extension which converts Python scripts (. py) into Microsoft Windows executables (.exe). These executables can run on a system without Python installed. It is the most common tool for doing so.

How do I run a Python script without terminal in Linux?

It's easier to just rename the script (and set it executable, and have proper shebang); but if you don't want the Terminal screen and don't mind a second file to invoke your script, Automator is probably the best option.

How do I run a script in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


3 Answers

Add a shebang:

#!/usr/bin/python

or

#!/usr/bin/env python

I prefer the second one, since Python can be anywhere like /usr/bin/python, /usr/local/bin/python etc. and second one ensure that you don't have to keep editing the shebang.

And then you can just execute it as ./script.py if it is executable.

like image 188
manojlds Avatar answered Oct 06 '22 01:10

manojlds


in your python script add this as your first line

#!/usr/bin/python

then in terminal do this chmod +x ./yourpythonscript.py

then from terminal execute as ./yourpythonscript.py

like image 24
Troydm Avatar answered Oct 06 '22 00:10

Troydm


Try ./script.py instead of script.py ... or ensure your current directory is in your path and script.py should work....

like image 36
ted Avatar answered Oct 06 '22 01:10

ted