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

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

问题描述

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

I know how to set it in my /etc/profile and in my environment variables.

但是如果我想在脚本中设置它呢?
是否导入os,sys?我如何做?

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 的值来初始化c $在Linux系统上,$ code>; 在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天全站免登陆