如何制作全局可调用的python程序?

How to make globally callable python program?

我写了一个模块并创建了一个setup.py来安装模块:

from setuptools import setup, find_packages

setup(
    name='mymodule',
    version='0.1',
    packages=find_packages(exclude=['test', 'test.*']),
    include_package_data=True,
    platforms='any',
    install_requires=[
        'lxml==3.3.5',
        'Pillow==3.0.0',
        'requests==2.2.1',
        'xmltodict==0.10.1',
        'pdfrw==0.2',
        'python-dotenv==0.4.0',
        'boto==2.39.0'
    ],
)

在同一个模块中,我还使用 getopt 为该模块编写了一个命令行界面。我想让此命令行界面全局可用,以便系统上的任何用户都可以执行以下操作:

$ mycliprogram -i inputfile.xml -o outputfile.txt

有人知道我如何在 setup.py 中包含 mycliprogram.py 以便系统上的任何人都可以从命令行使用它吗?

我会引用 documentation:

第一种方法是将你的脚本写在一个单独的文件中,比如你可能会写一个 shell 脚本:

funniest/
    funniest/
        __init__.py
        ...
    setup.py
    bin/
        funniest-joke
    ...

然后我们可以像这样在 setup() 中声明脚本:

setup(
    ...
    scripts=['bin/funniest-joke'],
    ...
)

当我们安装包时,setuptools 会将脚本复制到我们的 PATH 并使其可供一般使用。:

$ funniest-joke

您可以在 setup():

中使用 console-scripts(如 Sergey 所建议的)或 entry_points 参数
  entry_points={
      'console_scripts': [
          'mycliprogram=mymodule:whatever',
      ],
  },

这将创建一个 myclyprogram 包装器,可通过 $PATH 访问,它将在 mymodule 中调用 whatever。因此,如果您通过 pipsetup.py 安装您的模块,您将能够使用您直接从命令行提示符定义的任何选项调用 mycliprogram

更多信息:Command Line Scripts – Python Packaging Tutorial