简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM