向 Python sys.path 添加一个目录,以便每次使用 Python 时都包含它 [英] Add a directory to Python sys.path so that it's included each time I use Python

查看:38
本文介绍了向 Python sys.path 添加一个目录,以便每次使用 Python 时都包含它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,在尝试引用某些库代码时,我在 python 文件的顶部执行此操作:

Currently, when trying to reference some library code, I'm doing this at the top of my python file:

import sys
sys.path.append('''C:\code\my-library''')
from my-library import my-library

然后,只要会话处于活动状态,my-library 就会成为 sys.path 的一部分.如果我开始一个新文件,我必须记住再次包含 sys.path.append.

Then, my-library will be part of sys.path for as long as the session is active. If I start a new file, I have to remember to include sys.path.append again.

我觉得一定有更好的方法来做到这一点.如何使 my-library 可用于 Windows 机器上的每个 python 脚本,而不必每次都使用 sys.path.append?

I feel like there must be a much better way of doing this. How can I make my-library available to every python script on my windows machine without having to use sys.path.append each time?

推荐答案

只需将此路径添加到您的 PYTHONPATH 环境变量中即可.为此,请转到控制面板"/系统"/高级"/环境变量",然后在用户变量"部分中,检查您是否已经拥有 PYTHONPATH.如果是,请选择它并单击编辑",如果不是,请单击新建"以添加它.

Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.

PYTHONPATH 中的路径应该用;"分隔.

Paths in PYTHONPATH should be separated with ";".

这篇关于向 Python sys.path 添加一个目录,以便每次使用 Python 时都包含它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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