PYTHONPATH 环境变量...之后如何创建每个子目录?

Ale*_*lex 10 linux unix python environment-variables

我目前这样做:

PYTHONPATH=/home/$USER:/home/$USER/respository:/home/$USER/repository/python-stuff
Run Code Online (Sandbox Code Playgroud)

我怎样才能使 PYTHONPATH 可以包含所有子目录?

PYTHONPATH = /home/$USER/....and-all-subdirectories
Run Code Online (Sandbox Code Playgroud)

Jed*_*ith 15

这不是 PYTHONPATH 的工作方式;PYTHONPATH 将其搜索路径与 shell PATH 不同。假设我这样做:

$ mkdir /home/jsmith/python
$ cd /home/jsmith/python
$ touch a.py b.py
Run Code Online (Sandbox Code Playgroud)

这将在 Python 中工作(sys.path将包括当前目录):

$ cd /
$ PYTHONPATH=/home/jsmith/python python2.6

Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)
>>> import a, b   # Works
>>> quit()
Run Code Online (Sandbox Code Playgroud)

但是,子目录__init__.py在目录中存在时被视为包,否则被 PYTHONPATH忽略

$ mkdir /home/jsmith/python/pkg
$ cd /home/jsmith/python/pkg
$ touch __init__.py c.py d.py
$ cd /
$ PYTHONPATH=/home/jsmith/python python2.6

Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51)
>>> import a, b   # Works
>>> import c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named c
Run Code Online (Sandbox Code Playgroud)

要获取该子目录中的内容,这将起作用:

>>> from pkg import c   # Works
>>> import pkg.c        # Works
Run Code Online (Sandbox Code Playgroud)

要推出添加 PYTHONPATH 中每个子目录的解决方案,您需要将每个文件夹显式添加到 PYTHONPATH 或以sys.path编程方式。此行为是故意的,并且表现什么样shell路径。鉴于解释器在这方面对包的支持,肯定有更好的方法来完成你所追求的吗?

  • 伙计,我希望每个站点在拒绝您发帖权限之前都会检查您的其他帐户。从代表开始很糟糕,尤其是像一个 URL 限制这样的东西......(我有更多的参考资料给你,OP) (3认同)