Param
Param

Reputation: 729

How to run a Python module from any directory

I want to create a module called myscript that can be run via the command line from any directory.

I've created a setup.py file that looks like this:

import setuptools
setuptools.setup(
    name='myscript',
    version='1.0',
    packages=['lib.myscript'],
    install_requires=['setuptools', 'pandas >= 0.22.0', 'numpy >= 1.16.0'],
    python_requires='>=3.5'
)

After running python setup.py install, I'm still unable to run python -m myscript from anywhere but the directory the script is located in.

My folder structure looks like this:

lib
  myscript
    __init__.py (empty)
    __main__.py (the code that should run)

setup.py

Upvotes: 0

Views: 812

Answers (1)

R4444
R4444

Reputation: 2114

For that you have to set entry_points function in setup.py (and if I understood your question correctly).

Your setup.py becomes:

import setuptools
setuptools.setup(
    name='myscript',
    version='1.0',
    packages=setuptools.find_packages(),
    install_requires=['setuptools', 'pandas >= 0.22.0', 'numpy >= 1.16.0'],
    python_requires='>=3.5'
    entry_points={
        'console_scripts': [
            'myscript=myscript.__main__:main' # or any specific function you would like
        ]
    },
)

Here __main__ is a filename (in your case). And main is a function (you can change it to whatever function you would like). And myscript is your command.

Now you can run (maybe myscript in your case):

python -m pip install yourpackage

Then you can run your script from anywhere:

myscript

edit:

arrange your file structure like:

myscript
  myscript
    __init__.py (empty)
    __main__.py (the code that should run)
  setup.py

Upvotes: 2

Related Questions