python - sys.path 上的包,带有 init 导入名称,可以在内部使用,但不能从外部使用

标签 python package pythonpath

我有一个包 my_scripting_library 我想在计算机上的任何地方使用。它有一个 init.py:

from silo_functions import *

看起来像

my_scripting_library
  -__init__.py
  -silo_functions.py
  -test_stuff.py

test_stuff.py 看起来像:

#!/usr/bin/env python

from silo_functions import *

lines = read_lines('filepath.py')

print lines

在 bashrc 中:

export PYTHONPATH="${PYTHONPATH}:$LIBRARY"

其中 LIBRARY 是 my_scripting_library 的正确文件路径

In [1]: import sys

In [2]: sys.path
Out[2]: 
['',
 '/usr/bin',
 '/usr/lib/python2.7/site-packages/lxml-3.3.3-py2.7-linux-x86_64.egg',
 '/home/cchilders/scripts/python/my_scripting_library',
...
 '/home/cchilders/.ipython']

使用 from .silo_functions import * 运行 test_stuff 会导致:

Traceback (most recent call last):
  File "./test_stuff.py", line 3, in <module>
    from .silo_functions import *
ValueError: Attempted relative import in non-package

使用 from my_scripting_library.silo_functions import * 运行 test_stuff 原因:

Traceback (most recent call last):
  File "./test_stuff.py", line 3, in <module>
    from my_scripting_library.silo_functions import *
ImportError: No module named my_scripting_library.silo_functions

但是使用 from silo_functions import * 运行 test_stuff 可以工作:

它打印行

当然,我不能从其他文件夹使用这个包,这是真正的问题 - 我不想被迫将所有脚本扔到这个地方。这导致了巨大的问题,因为我不断地重复使用每个脚本的数十个函数,并且超过 5 个关于将文件夹制作为 python 包的教程从未工作过。为什么 python 路径上带有 init 的东西不是包?谢谢

最佳答案

可能是因为您已将“.../python/my_scripting_library”添加到路径中。但此文件夹中没有'my_scripting_library.py'

如果您想使用“my_scripting_library.silo_functions”,请尝试添加“/home/cchilders/scripts/python”(而不是“/home/cchilders/scripts/python/my_scripting_library”)小路。 因为“my_scripting_library”是模块。 Python会找到这个文件夹,在这个文件夹中找到__init__.py并将其标记为模块。

关于python - sys.path 上的包,带有 init 导入名称,可以在内部使用,但不能从外部使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859245/

相关文章:

python - 字符串替换组合

python - 尝试安装库 python 时出现 ImportError。

python - python 3.4 中 euclid.py 中的语法错误

Perl 模块命名约定

Python numpy 在 cmd 行中找到,但在脚本中没有

python - 使用 SQLAlchemy 在不经常使用的 Python/Flask 服务器上避免 "MySQL server has gone away"

python - 模块化 pow() 中的负幂

package - Xubuntu 上的 Debian 软件包,安装 debchange/dch?

python - 为什么带有尾随冒号的 PYTHONPATH 将当前目录添加到 sys.path?

python - 导入django不起作用? Python路径?