问题:在Python脚本中,如何设置PYTHONPATH?
我知道如何在/ etc / profile和环境变量中进行设置。
但是,如果我想在脚本中进行设置怎么办?是导入os,sys吗?我该怎么做?
I know how to set it in my /etc/profile and in my environment variables.
But what if I want to set it during a script?
Is it import os, sys? How do I do it?
回答 0
您没有设置PYTHONPATH
,而是向中添加条目sys.path
。这是应该在其中搜索Python软件包的目录列表,因此您只需将目录追加到该列表即可。
sys.path.append('/path/to/whatever')
实际上,sys.path
是通过分割PYTHONPATH
路径分隔符:
上的值来初始化的(在类似Linux的系统上,;
在Windows上)。
您也可以使用来添加目录site.addsitedir
,该方法还将考虑.pth
您传递的目录内存在的文件。(对于您在中指定的目录,情况并非如此PYTHONPATH
。)
You don’t set PYTHONPATH
, you add entries to sys.path
. It’s a list of directories that should be searched for Python packages, so you can just append your directories to that list.
sys.path.append('/path/to/whatever')
In fact, sys.path
is initialized by splitting the value of PYTHONPATH
on the path separator character (:
on Linux-like systems, ;
on Windows).
You can also add directories using site.addsitedir
, and that method will also take into account .pth
files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH
.)
回答 1
您可以通过os.environ
以下方式获取和设置环境变量:
import os
user_home = os.environ["HOME"]
os.environ["PYTHONPATH"] = "..."
但是,由于您的解释器已经在运行,因此不会起作用。你最好用
import sys
sys.path.append("...")
这是您PYTHONPATH
将在解释程序启动时转换为的数组。
You can get and set environment variables via os.environ
:
import os
user_home = os.environ["HOME"]
os.environ["PYTHONPATH"] = "..."
But since your interpreter is already running, this will have no effect. You’re better off using
import sys
sys.path.append("...")
which is the array that your PYTHONPATH
will be transformed into on interpreter startup.
回答 2
如果您sys.path.append('dir/to/path')
不加检查就放了它,则可以在中生成一个长列表sys.path
。为此,我建议这样做:
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
If you put sys.path.append('dir/to/path')
without check it is already added, you could generate a long list in sys.path
. For that, I recommend this:
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
回答 3
PYTHONPATH结尾于sys.path,您可以在运行时进行修改。
import sys
sys.path += ["whatever"]
PYTHONPATH ends up in sys.path, which you can modify at runtime.
import sys
sys.path += ["whatever"]
回答 4
您可以通过设置PYTHONPATH
,os.environ['PATHPYTHON']=/some/path
然后需要调用os.system('python')
以重新启动python shell,以使新添加的路径生效。
you can set PYTHONPATH
, by os.environ['PATHPYTHON']=/some/path
, then you need to call os.system('python')
to restart the python shell to make the newly added path effective.
回答 5
我的Linux也可以:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])