Python導入自定義路徑的方法
前言:
Python
可以引入指定路徑的文件,原理就是使用sys.path.append
加入到程序查找的路徑。
實驗目的:調用不同目錄的類和接口,entry
調用is_class
和is_method
的接口。
實驗過程:
使用sys.path.append('Dir1\\Dir2')
,把當前目錄下的“Dir1\\Dir2
”加入到python
查找文件的路徑下。import
方法或者類就會在Dir1\\Dir2路徑下查找。
測試目錄:C:\\Users\\OOXX\\Desktop\\test
目錄結構:
C:.
│ entry.py
│
└─Dir1
└─Dir2
│ is_class.py
│ is_method.py
is_method.py內容:
def to_do(): ? ? print('method to do')
is_class.py內容
class Class: ? ? def __init__(self): ? ? ? ? print('class init') ? ? ? ?? ? ? def to_do(self): ? ? ? ? print('class to do')
entry.py內容:
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()
開始執(zhí)行測試:
$ 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內。
到此這篇關于Python導入自定義路徑的方法的文章就介紹到這了,更多相關Python導入路徑內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
django生產環(huán)境搭建(uWSGI+django+nginx+python+MySQL)
本文主要介紹了django生產環(huán)境搭建,主要包括uWSGI+django+nginx+python+MySQL,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08詳解pytorch中squeeze()和unsqueeze()函數介紹
這篇文章主要介紹了詳解pytorch中squeeze()和unsqueeze()函數介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09Python單元測試工具doctest和unittest使用解析
這篇文章主要介紹了Python單元測試工具doctest和unittest使用解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09YOLOv5車牌識別實戰(zhàn)教程(一)引言與準備工作
這篇文章主要介紹了YOLOv5車牌識別實戰(zhàn)教程(一)引言與準備工作,在這個教程中,我們將一步步教你如何使用YOLOv5進行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下2023-04-04