前言:
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内容:
1
2
|
def to_do(): print ( 'method to do' ) |
is_class.py内容
1
2
3
4
5
6
|
class Class: def __init__( self ): print ( 'class init' ) def to_do( self ): print ( 'class to do' ) |
entry.py内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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() |
开始执行测试:
1
2
3
4
5
6
7
8
9
10
|
$ 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
'在环境变量的list内。
到此这篇关于Python导入自定义路径的方法的文章就介绍到这了,更多相关Python导入路径内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/obanaganastar/article/details/121994366