python导入自定义的类 vscode(一)

前言:在如何在一个py代码中导入另一个自定义的代码

方法一:采用vscode的debug方式添加配置文件(不能使用runcode直接跑,应该可以修改配置来解决这个问题)

方法二:__init__.py导入其他包(不好使用debug,应该可以修改配置文件)

方式三:python安装陌路的lib包下直接引用,可使用task.json方式发布到lib(复用性高,但扰乱标准库的)

方式四:引入同级目录下的包(方便代码可读性高,代码乱复用性底)

一、目录结构

|-.vscode

|----launch.json

|-excel

|----ct_totle_row

|----ctTotleRow.py

|-util

|-----__init__.py

|-----MyLogger.py

|-----excelUtil.py

|-.env

二、各文件内容

1、launch.json

在自动生成launch.json文件后,将运行时的环境加进去env和envFile

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: 当前文件",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "env": {"PYTHONPATH":"${workspaceRoot}"},
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}

 

2、.evn文件

引入模块util

PYTHONPATH=util

3、util\__init__.py

__init__.py文件写需要导入的文件

其中from .MyLogger代表文件名,import MyLogger 代表模块中的类

from .excelUtil import excelUtil 
from .MyLogger import MyLogger

 

4、util\MyLogger.py自定义的模块文件

import logging
from logging import handlers
import time
import os
 
# 日志输出格式
LOGGING_FORMATTER = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
# 日志文件夹
FILEURL = './log/'
# 日志级别
LEVEL='info'

class MyLogger():
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename= '',fileUrl = FILEURL,level=LEVEL,when='D',backCount=10,fmt=LOGGING_FORMATTER):
        isExists=os.path.exists(FILEURL)
        if not isExists:
            os.makedirs(FILEURL) 
        timestr = time.strftime("%Y-%m-%d", time.localtime())
        filename = fileUrl + filename + timestr + '.log'
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
        # S 秒  M 分 H 小时、 D 天、 W 每星期(interval==0时代表星期一) midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)

5、excel\ct_totle_row\ctTotleRow.py

实际写代码的地方,在此引入其他类

from util import MyLogger

if __name__ == '__main__':
    log = MyLogger()
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')

三、其他

1、如何生成launch.json

点击最左边侧边栏第四个(从上往下数)

 

2、什么是__init__.py文件

如果目录中存在该文件,该目录就会被识别为 module package

该文件也可以写代码,将一些公共模块放在这里

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值