Linux 在 Python 脚本中,如何设置 PYTHONPATH?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3108285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python script, how do I set PYTHONPATH?
提问by TIMEX
I know how to set it in my /etc/profile and in my environment variables.
我知道如何在我的 /etc/profile 和我的环境变量中设置它。
But what if I want to set it during a script? Is it import os, sys? How do I do it?
但是如果我想在脚本中设置它呢?是导入操作系统,系统吗?我该怎么做?
采纳答案by David Z
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.
您没有设置PYTHONPATH
,而是将条目添加到sys.path
。这是一个应该搜索 Python 包的目录列表,因此您可以将您的目录附加到该列表中。
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).
实际上,sys.path
是通过分割PYTHONPATH
路径分隔符:
上的值来初始化的(在类 Linux 系统上,;
在 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
.)
您还可以使用 添加目录site.addsitedir
,该方法还将考虑.pth
您传递的目录中存在的文件。(您在 中指定的目录不是这种情况PYTHONPATH
。)
回答by miku
You can get and set environment variables via os.environ
:
您可以通过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.
这是您PYTHONPATH
将在解释器启动时转换成的数组。
回答by unbeli
PYTHONPATH ends up in sys.path, which you can modify at runtime.
PYTHONPATH 最终在sys.path 中,您可以在运行时修改它。
import sys
sys.path += ["whatever"]
回答by Francisco Manuel Garca Botella
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:
如果你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
回答by tesla1060
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.
可以设置PYTHONPATH
, by os.environ['PATHPYTHON']=/some/path
, 然后需要调用os.system('python')
重启python shell使新添加的路径生效。
回答by lashgar
I linux this works too:
我 linux 这也有效:
import sys
sys.path.extend(["/path/to/dotpy/file/"])