在Python脚本中,如何设置PYTHONPATH?
我知道如何将其设置在我的/ etc / profile和我的环境variables中。
但是如果我想在剧本中设置呢? 是import操作系统,系统? 我该怎么做?
你不设置PYTHONPATH ,你添加条目到sys.path 。 这是一个应该searchPython包的目录列表,所以你可以将你的目录附加到列表中。 
 sys.path.append('/path/to/whatever') 
 事实上, sys.path是通过在path分隔符( :在类Linux系统上,在Windows上)分割PYTHONPATH的值来初始化的。 
 您也可以使用site.addsitedir添加目录,该方法也将考虑您传递的目录中存在的.pth文件。  (对于在PYTHONPATH指定的目录,情况不会如此)。 
 你可以通过os.environ获取和设置环境variables: 
 import os user_home = os.environ["HOME"] os.environ["PYTHONPATH"] = "..." 
但是既然你的解释器已经运行了,这将不起作用。 你最好使用
 import sys sys.path.append("...") 
 这是数组,你的PYTHONPATH将被转换为解释器启动。 
对不起重新打开这个问题,但我认为它可以帮助某人:
 如果你把sys.path.append('dir/to/path')没有检查它已经添加了,你可以在sys.path生成一个长列表。 为此,我build议: 
 import sys import os # if you want this directory try: sys.path.index('/dir/path') # Or os.getcwd() for this directory except ValueError: sys.path.append('/dir/path') # Or os.getcwd() for this directory 
如果我惹恼某人重新提出这个问题,我很抱歉。
PYTHONPATH最终在sys.path中 ,您可以在运行时修改它。
 import sys sys.path += ["whatever"]