Python 在 Raspberry 中记录文件错误

log file error in in Raspberry with Python

我在我的 Raspberry Pi 中使用 Python3,我有一个代码,有人与我分享,显示以下行来记录日志文件:

logging.basicConfig(filename='/Desktop/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

但是当我在我的 Raspberry 上使用 Python 托盘 运行 代码时,我收到以下错误:

Traceback (most recent call last):
File "test.py", line 709, in <module>
main(sys.argv)
File "test.py", line 641, in main
logging.basicConfig(filename='/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)
File "/usr/lib/python3.7/logging/__init__.py", line 1900, in basicConfig
h = FileHandler(filename, mode)
File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/morning/RER-execution-logs.txt'

我也手动创建了目录和文件,但我得到了另一个错误:

Traceback (most recent call last):
File "test.py", line 709, in <module>
main(sys.argv)
File "test.py", line 641, in main
logging.basicConfig(filename='/var/log/morning/RER-execution-logs.txt',format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)
File "/usr/lib/python3.7/logging/__init__.py", line 1900, in basicConfig
h = FileHandler(filename, mode)
File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/var/log/morning/RER-execution-logs.txt

我做错了什么

这只是因为您尝试登录的文件并不实际存在。您可以手动创建它,也可以使用以下版本的 Python 脚本为您创建它,如果它还不存在的话:

import logging, os

logPath = '/Desktop/var/log/morning/RER-execution-logs.txt'

if not os.path.exists(logPath):
    open(logPath, 'w+').close()

logging.basicConfig(filename=logPath,format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO)

但是请确保该日志文件的路径实际上是正确的。为了更加确定,请使用绝对路径。您正在寻找类似的东西:

/home/pi/Destkop/...