Home > Backend Development > Python Tutorial > How to add search path in Python

How to add search path in Python

WBOY
Release: 2023-05-13 10:28:05
forward
3091 people have browsed it

Python adds search path

1. Add

to the program using sys.path, for example:

import sys
sys.path.append('/Users/username/Documents/')

sys.path
Copy after login

and you can use sys.path to output what is currently included directory.

2. Use the .pth file to add

Add a .pth file to the lib/python/site-packages/ directory in the directory where lib/python is installed.

What you need to pay attention to here is where the directory where python is installed is.

For example, if you use the my_project environment of the virtual environment in conda, it should be /Users/username/opt/anaconda3/envs/fealpy Add a mypath.pth file to the directory /lib/python3.8/site-packages. The content in

mypath.pth is the directory to be added:

/Users/username/Documents/
/Users/username/Downloads/
Copy after login

After adding, the same You can call sys.path in python to view:

import sys
sys.path
Copy after login

Attachment: python temporarily adds a search path

Put the address of your project in the sys.path list to facilitate the quick import of modules.

import os, sys

# 获取当前用户的home目录
module = os.path.expanduser('~')
# 打印当前用户的home目录
print(module)
# 定义home目录的搜索优先级,0为最高优先级
# sys.path.insert()加入的也是临时搜索路径,程序退出后失效。
sys.path.insert(0, module)
# 打印搜索路径
print(sys.path)
Copy after login

The above is the detailed content of How to add search path in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template