【问题标题】:`ModuleNotFoundError` when running script from `console_scripts` but not when importing via Python console从“console_scripts”运行脚本时出现“ModuleNotFoundError”,但通过 Python 控制台导入时不会出现
【发布时间】:2020-05-20 20:12:12
【问题描述】:

我正在尝试设置一个合适的 Python 包进行分发,但我的 setup.py 文件的 console_scripts 属性遇到了问题。我的设置中有以下内容:

<...>
entry_points={"console_scripts": ["solve_cipher=cipher_solver.solve_cipher:main"]}
<...>

我已经打包并发送到测试 PyPI,然后在新的虚拟环境中安装我的打包。现在,solve_cipher 命令可用,但运行它会给我:

$ solve_cipher 
Traceback (most recent call last):
  File "/Users/markus/.virtualenvs/cipher_solver_debug_pypi/bin/solve_cipher", line 6, in <module>
    from cipher_solver.solve_cipher import main
ModuleNotFoundError: No module named 'cipher_solver'

但是,如果我只是启动 Python 并运行相同的导入行,它就可以正常工作:

$ python
>>> from cipher_solver.solve_cipher import main
>>>

为什么会这样?我的项目布局如下:

cipher_solver
    <...>
    cipher_solver
        consts.py
        simple.py
        solve_cipher.py
        utils.py
    <...>
    setup.py

【问题讨论】:

  • which python? head -1 /Users/markus/.virtualenvs/cipher_solver_debug_pypi/bin/solve_cipher?
  • @phd #!/Users/markus/.virtualenvs/cipher_solver_debug_pypi/bin/python3.7
  • 看起来不错。和which python一样吗?当您从命令行import cipher_solver 时,当前目录是什么? setup.py 所在的那个?
  • 谢谢!我解决了这个问题,请参阅下面的答案。
  • @phd 嗯,我想我说得太早了。是的,它们是相同的 Python 二进制文件,我从 setup.py 所在的位置运行它。还有其他想法吗?

标签: python python-3.x setuptools


【解决方案1】:

我发现了问题。我在setup.py 中使用了setuptools.find_packages(),结果发现该方法需要包和子包中的__init__.py 文件才能找到它们。我认为这在 Python 3.3+ 中不再需要,但显然在某些情况下。

【讨论】:

  • 您可能想试试find_namespace_packages。根据您的具体要求,可能会有所帮助。
  • @sinoroc 我没有任何命名空间包。
  • 据我所知,是否有命名空间包并不重要。也许函数的名称有点误导,不确定。无论如何,上次我尝试这个函数时能够收集不包含任何 __init__.py 包初始化程序的包。但老实说,我还是更喜欢将__init__.py 放在我所有的包中,并使用普通的find_packages 函数。我只是想我会提到这个替代方案。
  • 谢谢,不胜感激。我对__init__.py 文件没问题,只要我能让它工作:)
猜你喜欢
  • 2017-08-12
  • 2020-08-23
  • 2019-03-22
  • 2023-03-15
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多