当前位置:   article > 正文

python相对路径的引用注意事项_python 相对路径引用

python 相对路径引用

在上一篇文章中(python工程中使用logging_sogobaidu的博客-CSDN博客)提到了loggingConfig引入yaml配置文件,在使用systemctl启动工程后,logging日志没有打印出来。但是,在工程里面下直接使用python3 ****.py时,日志是可以正常打印。当时没找到原因,今天发现了原因。讲原因前,先说下python如何定位path的。

1、path = os.path.abspath(__file__)

获取到的path是.py文件存在的目录。

2、path = os.path.abspath('.')

获取到的是执行python3时所在的目录。

3、在loggingBuild.py中引用yaml文件时,没有使用绝对路径。我们一般理解,没有使用绝对路径,python应该是在文件的同级目录下查找yaml文件。但是,根据观察,python不是在.py文件的同级目录下查询yaml文件,而是在执行启动命令时所在的目录中查找yaml。

4、systemctl start reminder是root用户启动,目录是默认的 / 根目录。这就导致loggingBuild.py未能够查找到yaml文件,导致日志无法正确打印。

5、以上弯路主要还是因为对python的基本概念不了解导致的。python从10多年前陆陆续续的使用,但是真没有在工程上使用,也没有详细的看过Python的原理。

6、对loggingBuild.py进行了调整,以loggingBuild.py文件的绝对路径为基础,拼接出完整的yaml的绝对路径。

  1. import yaml
  2. import logging.config
  3. import os
  4. path = os.path.abspath(__file__)
  5. for i in range(1):
  6. path = os.path.dirname(path)
  7. print(path)
  8. path = os.path.join(path, 'loggingConfig.yaml')
  9. if os.path.exists(path):
  10. with open(path, "r") as f:
  11. # 1.config=yaml.load(stream,Loader=yaml.FullLoader)
  12. # 2.config=yaml.safe_load(stream)
  13. # 3.config = yaml.load(stream, Loader=yaml.CLoader)
  14. config = yaml.load(f, Loader=yaml.FullLoader)
  15. logging.config.dictConfig(config)

systemctl start reminder

可以看到日志正常的打印出来:

  1. pi@raspberrypi4:/ $ tail -100f info.log
  2. 2022-01-16 20:58:18,897 - commonRemindForWeather - 191 - INFO - 3069516608 - {'Linux': '/home/pi/Music/t0.mp3', 'Windows': 'C:/Users/Administrator/Downloads/t0.mp3'}
  3. 2022-01-16 20:58:18,897 - commonRemindForWeather - 192 - INFO - 3069516608 - Linux
  4. 2022-01-16 20:58:18,913 - commonRemindForWeather - 205 - INFO - 3069516608 - holiday.getStatus()=H
  5. 2022-01-16 20:58:18,915 - commonRemindForWeather - 216 - INFO - 3069516608 - 3.36
  6. 2022-01-16 20:58:25,864 - commonRemindForWeather - 191 - INFO - 3069516608 - {'Linux': '/home/pi/Music/sunny_new.mp3', 'Windows': 'C:/Users/Administrator/Downloads/sunny_new.mp3'}
  7. 2022-01-16 20:58:25,866 - commonRemindForWeather - 192 - INFO - 3069516608 - Linux
  8. 2022-01-16 20:58:25,872 - commonRemindForWeather - 205 - INFO - 3069516608 - holiday.getStatus()=H
  9. 2022-01-16 20:58:25,877 - commonRemindForWeather - 216 - INFO - 3069516608 - 3.456
  10. 2022-01-16 20:58:32,970 - commonRemindForWeather - 191 - INFO - 3069516608 - {'Linux': '/home/pi/Music/t1.mp3', 'Windows': 'C:/Users/Administrator/Downloads/t1.mp3'}

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号