简体   繁体   中英

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. The class_file.py contains a logger, defined as follows:

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:

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 "." 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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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