Reputation: 1153
How can I run a python script with my own command line name like myscript
without having to do python myscript.py
in the terminal?
See also: Why do I get non-Python errors like "./xx.py: line 1: import: command not found" when trying to run a Python script on Linux? for a common problem encountered while trying to set this up on Linux/Mac, or 'From/import' is not recognized as an internal or external command, operable program or batch file for the equivalent problem on Windows.
Upvotes: 98
Views: 231904
Reputation: 146
The simplest way that comes to my mind is to use "pyinstaller".
pip install pyinstaller
pyinstaller maincode.py
I hope that this solution helps you. GL
Upvotes: 2
Reputation: 1955
Another related solution which some people may be interested in. One can also directly embed the contents of myscript.py into your .bashrc file on Linux (should also work for MacOS I think)
For example, I have the following function defined in my .bashrc for dumping Python pickles to the terminal, note that the ${1}
is the first argument following the function name:
depickle() {
python << EOPYTHON
import pickle
f = open('${1}', 'rb')
while True:
try:
print(pickle.load(f))
except EOFError:
break
EOPYTHON
}
With this in place (and after reloading .bashrc), I can now run depickle a.pickle
from any terminal or directory on my computer.
Upvotes: 3
Reputation: 1069
The best way, which is cross-platform, is to create setup.py
, define an entry point in it and install with pip
.
Say you have the following contents of myscript.py
:
def run():
print('Hello world')
Then you add setup.py
with the following:
from setuptools import setup
setup(
name='myscript',
version='0.0.1',
entry_points={
'console_scripts': [
'myscript=myscript:run'
]
}
)
Entry point format is terminal_command_name=python_script_name:main_method_name
Finally install with the following command.
pip install -e /path/to/script/folder
-e
stands for editable, meaning you'll be able to work on the script and invoke the latest version without need to reinstall
After that you can run myscript
from any directory.
Upvotes: 85
Reputation: 549
I usually do in the script:
#!/usr/bin/python
... code ...
And in terminal:
$: chmod 755 yourfile.py
$: ./yourfile.py
Upvotes: 12
Reputation: 47770
Add a shebang line to the top of the script:
#!/usr/bin/env python
Mark the script as executable:
chmod +x myscript.py
Add the dir containing it to your PATH
variable. (If you want it to stick, you'll have to do this in .bashrc
or .bash_profile
in your home dir.)
export PATH=/path/to/script:$PATH
Upvotes: 149