简体   繁体   English

使用 argparse 和 setuptools 制作 CLI

[英]Make CLI with argparse and setuptools

I have a module sfind.py.我有一个模块 sfind.py。 How can I do this so that I can run the script by the file name without the py prefix?我该如何做到这一点,以便我可以通过不带 py 前缀的文件名运行脚本?

 python sfind instead python sfind.py

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.我尝试使用 setuptools 来完成,在同一目录中创建了新文件 setup.py。

setup.py设置文件

from setuptools import setup从 setuptools 导入设置

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 将您的模块称为python sfind Setuptools will allow you to call by just sfind . Setuptools 将允许您仅通过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.若要称之为python sfind ,你必须让你的sfind一个模块,你可以通过使蟒蛇目录为此sfind__init__.py__main__.pysfind.py在目录中。 Then, you can call with just python sfind .然后,您可以仅使用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 .如果您只想使用sfind调用它,您可以使用设置工具,但建议您提供可调用函数(例如sfind=sfind.sfind:main )而不是模块本身( __main__ )作为您的entry_points You can then do either python setup.py install or python setup.py sdist then pip install .然后,您可以执行python setup.py installpython setup.py sdist然后执行pip install

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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