简体   繁体   English

将类导入子文件夹中的另一个文件时处理记录器目录

[英]Handling logger directory when importing a class into another file in child folder

I have the following class directory:我有以下类目录:

project_directory/
....__init__.py
....class_file.py
....logger_folder/
....unittest_folder/
.........class_file_test.py

I have a class defined in class_file.py and I want to test it from class_file_test.py in the unittest_folder.我在 class_file.py 中定义了一个类,我想从 unittest_folder 中的 class_file_test.py 中对其进行测试。 The class_file.py contains a logger, defined as follows: class_file.py 包含一个记录器,定义如下:

import logging

logging.basicConfig(level=logging.INFO,
                    filename='./logger_folder/class_file.log')
logger = logging.getLogger('my_logger')

To test class_file from the unittest folder, I imported class_file using the following code in class_file_test.py:为了从 unittest 文件夹中测试 class_file,我在 class_file_test.py 中使用以下代码导入了 class_file:

import sys
sys.path.append('..')

from class_file import MyClass

When I run this code, I get the following error:当我运行此代码时,出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\project_folder\\unittest_folder\\logger_folder\\class_file.log'

So, clearly the unittest imported the class_file code and then used "."因此,显然单元测试导入了 class_file 代码,然后使用了“.”。 I use to define the filename for the logger relative to its own path.我用来定义记录器相对于它自己的路径的文件名。 What is the right way to handle locating directories in such a file structure?在这样的文件结构中处理定位目录的正确方法是什么?

The problem is your directory setting.问题在于您的目录设置。 Currently you are using relative path of current working directory.当前您正在使用当前工作目录的相对路径。 In practice, you should use absolute path or relavetive path of that file's directory.实际上,您应该使用该文件目录的绝对路径或相对路径。

from os.path import join, dirname, abspath
print(join(dirname(abspath(__file__)), "file.log"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM