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()

开始执行测试

$ 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内。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值