简体   繁体   中英

Make CLI with argparse and setuptools

I have a module sfind.py. How can I do this so that I can run the script by the file name without the py prefix?

 python sfind instead python sfind.py

sfind.py

import argparse


def createParser():
    some logic
    return parser

def main(namespace):
    some logic


if __name__ == '__main__':
    parser = createParser()
    namespace = parser.parse_args()
    main(namespace)

I tried to do it with setuptools, maked new file setup.py in same directory.

setup.py

from setuptools import setup

setup(
    name='sfind',
    version='0.1',
    packages=['sfind'],
    entry_points={
    'console_scripts': [
        'sfind=sfind:__main__'
    ]
})

But error occurred

python: can't open file 'sfind': [Errno 2] No such file or directory

Can anybody help me do it right?

File structure:

-sfind
  --__init__.py
  --__main__.py
  --sfind.py
  --test.py

You don't need setuptools to call your module as python sfind . Setuptools will allow you to call by just sfind . To call it with python sfind , you have to make your sfind a module and you can do this by making a python directory sfind with __init__.py , __main__.py , and sfind.py in the directory. Then, you can call with just python sfind . If you just want to call it with sfind , you can use setup tools, but it is recommended you provide callable function (eg sfind=sfind.sfind:main ) instead of module itself ( __main__ ) as your entry_points . You can then do either python setup.py install or python setup.py sdist then pip install .

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