日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python導(dǎo)入自定義路徑的方法_python

作者:決戰(zhàn)北京城 ? 更新時(shí)間: 2022-06-27 編程語(yǔ)言

前言:

Python可以引入指定路徑的文件,原理就是使用sys.path.append加入到程序查找的路徑。

實(shí)驗(yàn)?zāi)康模?/strong>調(diào)用不同目錄的類(lèi)和接口,entry調(diào)用is_classis_method的接口。

實(shí)驗(yàn)過(guò)程:

使用sys.path.append('Dir1\\Dir2'),把當(dāng)前目錄下的“Dir1\\Dir2”加入到python查找文件的路徑下。
import方法或者類(lèi)就會(huì)在Dir1\\Dir2路徑下查找。

測(cè)試目錄:C:\\Users\\OOXX\\Desktop\\test

目錄結(jié)構(gòu):

C:.
│ ?entry.py

└─Dir1
? ? └─Dir2
? ? ? ? │ ?is_class.py
? ? ? ? │ ?is_method.py

is_method.py內(nèi)容:

def to_do():
? ? print('method to do')

is_class.py內(nèi)容

class Class:
? ? def __init__(self):
? ? ? ? print('class init')
? ? ? ??
? ? def to_do(self):
? ? ? ? print('class to do')

entry.py內(nèi)容:

import sys
?
sys.path.append('Dir1\\Dir2')
import is_method
from ? is_class import Class
?
print(sys.path)
print('----------------------------------------------------')
?
print('class import example.............................')
Class().to_do()
?
print('')
print('method import example............................')
is_method.to_do()

開(kāi)始執(zhí)行測(cè)試:

$ python entry.py
['C:\\Users\\OOXX\\Desktop\\test', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\Ouyanghy\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\win32', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Ouyanghy\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\Pythonwin',?
'Dir1\\Dir2']
----------------------------------------------------
class import example.............................
class init
class to do
?
method import example............................
exec to do

打印sys.path可以看到'Dir1\\Dir2'在環(huán)境變量的list內(nèi)。

原文鏈接:https://blog.csdn.net/obanaganastar/article/details/121994366