How do I install a script to run anywhere from the command line?

Viewed 64229

If I have a basic Python script, with it's hashbang and what-not in place, so that from the terminal on Linux I can run

/path/to/file/MyScript [args]

without executing through the interpreter or any file extensions, and it will execute the program.

So would I install this script so that I can type simply

MyScript [args]

anywhere in the system and it will run? Can this be implemented for all users on the system, or must it be redone for each one? Do I simply place the script in a specific directory, or are other things necessary?

10 Answers

you can also use setuptools (https://pypi.org/project/setuptools/)

  1. your script will be:
def hi():
    print("hi")

(suppose the file name is hello.py)

  1. also add __init__.py file next to your script (with nothing in it).

  2. add setup.py script, with the content:

#!/usr/bin/env python3

import setuptools

install_requires = [
        'WHATEVER PACKAGES YOU NEED GOES HERE'
        ]

setuptools.setup(
    name="some_utils",
    version="1.1",
    packages=setuptools.find_packages(),
    install_requires=install_requires,
    entry_points={
        'console_scripts': [
            'cool_script = hello:hi',
        ],
    },
    include_package_data=True,
    )

  1. you can now run python setup.py develop in this folder
  2. then from anywhere, run cool_script and your script will run.

Just create symbolic link to your script in /usr/local/bin/:

sudo ln -s /path/to/your/script.py /usr/local/bin/script

i find a simple alias in my ~/.bash_profile or ~/.zshrc is the easiest:

alias myscript="python path/to/my/script.py"

Related