在 Python 脚本中,如何设置 PYTHONPATH? [英] In Python script, how do I set PYTHONPATH?

查看:33
本文介绍了在 Python 脚本中,如何设置 PYTHONPATH?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在我的/etc/profile 和我的环境变量中设置它.

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?

推荐答案

您没有设置 PYTHONPATH,而是将条目添加到 sys.path.这是一个应该搜索 Python 包的目录列表,因此您可以将您的目录附加到该列表中.

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')

实际上,sys.path 是通过在路径分隔符上分割PYTHONPATH 的值来初始化的(: 在类似Linux 的系统上), ; 在 Windows 上).

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

您还可以使用 site.addsitedir 添加目录,并且该方法还将考虑您传递的目录中存在的 .pth 文件.(对于您在 PYTHONPATH 中指定的目录,情况并非如此.)

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.)

这篇关于在 Python 脚本中,如何设置 PYTHONPATH?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆