Python 记录;无法创建日志文件
Python logging; Unable to create log files
我正在尝试创建 logFile.log
使用:
logging.basicConfig(filename='logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')
但是,我 运行 陷入 OS-错误:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/jaypuzhakkara/Documents/python projects/BOSAPI/demo1/demo1.py", line 28, in <module>
logging.basicConfig(filename='logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1976, in basicConfig
h = FileHandler(filename, mode)
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1143, in __init__
StreamHandler.__init__(self, self._open())
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1172, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
OSError: [Errno 30] Read-only file system: '/logFile.log'
如果我明确提供 filename= 的路径,错误就会消失,但我想在相同的目录中创建 logFile.log脚本被放置。我该如何实现?
我通过 xlwings
从 Excel 调用我的脚本,我发现工作目录实际上是 /
(尽管脚本和 .xlsm 都放在其他地方) .
所以我只需要检索脚本的路径,然后在 logging.basicConfig
:
中提供它
script_path = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(filename=script_path +'/logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')```
我正在尝试创建 logFile.log
使用:
logging.basicConfig(filename='logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')
但是,我 运行 陷入 OS-错误:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/jaypuzhakkara/Documents/python projects/BOSAPI/demo1/demo1.py", line 28, in <module>
logging.basicConfig(filename='logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1976, in basicConfig
h = FileHandler(filename, mode)
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1143, in __init__
StreamHandler.__init__(self, self._open())
File "/Users/jaypuzhakkara/anaconda3/lib/python3.8/logging/__init__.py", line 1172, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
OSError: [Errno 30] Read-only file system: '/logFile.log'
如果我明确提供 filename= 的路径,错误就会消失,但我想在相同的目录中创建 logFile.log脚本被放置。我该如何实现?
我通过 xlwings
从 Excel 调用我的脚本,我发现工作目录实际上是 /
(尽管脚本和 .xlsm 都放在其他地方) .
所以我只需要检索脚本的路径,然后在 logging.basicConfig
:
script_path = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(filename=script_path +'/logFile.log', filemode = 'a', level=logging.ERROR, format='%(asctime)s:%(levelname)s:%(message)s')```