3 回答

TA贡献1773条经验 获得超3个赞
由于我无法查看您的特定文件,因此我将仅解释我通常如何解决此问题。
这就是我通常设置命令行界面(cli)工具的方式。项目文件夹如下所示:
Projectname
├── modulename
│ ├── __init__.py # this one is empty in this example
│ ├── cli
│ │ ├── __init__.py # this is the __init__.py that I refer to hereafter
│ ├── other_subfolder_with_scripts
├── setup.py
其中所有功能都在模块名称文件夹和子文件夹中。在我的我有:__init__.py
def main():
# perform the things that need to be done
# also all imports are within the function call
print('doing the stuff I should be doing')
但我认为您也可以将您想要的内容导入到 中,并且仍然以我在 中的方式引用它。在我们有:__init__.pysetup.pysetup.py
import setuptools
setuptools.setup(
name='modulename',
version='0.0.0',
author='author_name',
packages=setuptools.find_packages(),
entry_points={
'console_scripts': ['do_main_thing=modulename.cli:main'] # so this directly refers to a function available in __init__.py
},
)
现在安装软件包,然后如果它已安装,您可以调用:pip install "path to where setup.py is"
do_main_thing
>>> doing the stuff I should be doing
对于我使用的文档:https://setuptools.readthedocs.io/en/latest/。
我的建议是从这里开始,慢慢添加你想要的功能。然后一步一步地解决你的问题,比如添加 README.md 等。

TA贡献1828条经验 获得超13个赞
我不同意其他答案。您不应在__init__.py中运行脚本,而应在__main__.py中运行脚本。
Projectfolder
├── formatter
│ ├── __init__.py
│ ├── cli
│ │ ├── __init__.py # Import your class module here
│ │ ├── __main__.py # Call your class module here, using __name__ == "__main__"
│ │ ├── your_class_module.py
├── setup.py
如果您不想提供自述文件,只需删除该代码并手动输入说明即可。
我使用 https://setuptools.readthedocs.io/en/latest/setuptools.html#find-namespace-packages 而不是手动设置包。
现在,您可以像以前一样运行来安装软件包。pip install ./
完成运行后:.它运行您在 CLI 文件夹(或您调用的任何内容)中创建的__main__.py文件。python -m formatter.cli arguments
关于打包模块的一个重要注意事项是,您需要使用相对导入。例如,您将在其中使用。如果要从相邻文件夹导入某些内容,则需要两个点。from .your_class_module import YourClassModule__init__.pyfrom ..helpers import HelperClass

TA贡献2080条经验 获得超4个赞
我不确定这是否有帮助,但通常我使用轮包打包我的python脚本:
pip install wheel python setup.py sdist bdist_wheel
完成这两个命令后,将在“dist”文件夹中创建一个whl包,然后您可以将其上传到PyPi并从那里下载/安装,也可以使用“pip install ${PackageName}.py”离线安装它。
这是一个有用的用户指南,以防万一有我没有解释的其他事情:
https://packaging.python.org/tutorials/packaging-projects/
添加回答
举报