我目前这样做:
PYTHONPATH=/home/$USER:/home/$USER/respository:/home/$USER/repository/python-stuff
我怎样才能使PYTHONPATH包含所有子目录?
PYTHONPATH = /home/$USER/....and-all-subdirectories
解决方法
这不是PYTHONPATH的作用方式; PYTHONPATH将其搜索路径与shell PATH区别对待.假设我这样做:
$mkdir /home/jsmith/python $cd /home/jsmith/python $touch a.py b.py
这将在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()
但是,当目录中存在__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,b # Works >>> import c Traceback (most recent call last): File "<stdin>",line 1,in <module> ImportError: No module named c
要获得该子目录中的某些内容,这将起作用:
>>> from pkg import c # Works >>> import pkg.c # Works
要添加添加了PYTHONPATH中每个子目录的解决方案,您需要以编程方式将每个文件夹显式添加到PYTHONPATH或sys.path.此行为是故意的,并且与shell PATH无关.鉴于口译员在这方面对包裹的支持,肯定有更好的方法来实现你所追求的目标吗?