Python的setup.py安装的CLI脚本不允许导入相同的模块

时间:2015-05-13 17:28:11

标签: python module setuptools

我想创建一个名为knife的python应用程序,可以从CLI执行,问题是它无法导入模块。我遵循与Django项目相同的文件夹结构以供参考。

我的目录结构如下:

knife/
    knife/
        bin/
            knife-cli.py
        core/
            main/
                __init__.py
            __init__.py
        __init__.py
    setup.py

我的setup.py看起来像这样:

#!/usr/bin/env python

from setuptools import setup, find_packages

exclude = ['knife.bin']

setup(name='Knife',
      version='0.3',
      description='Very cool project',
      author='John Doe',
      author_email='author@email.com',
      packages=find_packages(exclude=exclude),
      include_package_data=True,
      scripts=['knife/bin/knife-cli.py'],
      entry_points={
        'console_scripts': [
            'knife-cli = knife.core.main:main'
        ]
      },
      zip_safe=False,
     )

我的knife/core/main/__init__.py包含main()个功能,我的knife/bin/knife-cli.py看起来像这样:

#!/usr/bin/env python

from knife.core import main

if __name__ == "__main__":
    main.main()

因此在使用setup.py install安装模块之后,我尝试运行knife-cli但继续抛出此错误:

$ knife-cli 
Traceback (most recent call last):
  File "/usr/bin/knife-cli", line 9, in <module>
    load_entry_point('Knife==0.3', 'console_scripts', 'knife-cli')()
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 468, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2563, in load_entry_point
    return ep.load()
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2254, in load
    ['__name__'])
  File "/usr/bin/knife.py", line 4, in <module>
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 646, in run_script
    self.require(requires)[0].run_script(script_name, ns)
  File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 1559, in run_script
    raise ResolutionError("No script named %r" % script_name)
pkg_resources.ResolutionError: No script named 'knife.py'

真正发生了什么?我该如何解决呢?

2 个答案:

答案 0 :(得分:5)

知道了,脚本正在执行旧的/usr/bin/knife.pyc文件,我刚删除它,现在效果很好。

答案 1 :(得分:4)

您还需要更多__init__个。 __init__.py文件告诉python该文件夹是python模块。您正在将这些作为模块重新设置在安装脚本中,因此您需要告诉python它们是模块。

knife/
    knife/
        bin/
            knife-cli.py
        core/
            main/
                __init__.py
            __init__.py
        __init__.py
    setup.py

那应该解决主要问题。但是,您还要声明两个脚本,一个使用scripts部分,另一个使用console_scripts。控制台脚本实际上会为您创建脚本,因此您不需要在&#34; bin&#34;中包含您自己的脚本。

这是一个更好的setup.py给你:(注意我刚刚删除了脚本部分)

#!/usr/bin/env python

from setuptools import setup, find_packages

exclude = ['knife.bin']

setup(name='Knife',
      version='0.3',
      description='Very cool project',
      author='John Doe',
      author_email='author@email.com',
      packages=find_packages(exclude=exclude),
      include_package_data=True,
      entry_points={
        'console_scripts': [
            'knife-cli = knife.core.main:main'
        ]
      },
      zip_safe=False,
     )