简体   繁体   中英

Python package: Can I look for config/yml file from project directory which called it?

I am writing a Python package that contains a bunch of utility type functions that are specific to our team so they can install, import, and use them. Some of these functions access services that require authentication, so in the READ Me file, I have instructed them to create a YAML file in their project directory which houses their credentials.

When they import this package and call a function from it, is there a way for the package to look for this YAML file in the directory from which call it? Or do they need to parse the file themselves and pass the credentials as parameters into the function itself?

The __file__ variable contains the name or path the Python program. We can use functions from the os.path submodule to use this to get a file (in my example below called password.yml ).

import os.path
prog = __file__
directory = os.path.dirname(os.path.abspath(prog))
print(os.path.join(directory, 'password.yml'))

abspath converts the name to an absolute file (starting at the filesystem root). dirname removes the last (filename) component, leaving the directory, and join puts the directory path and the filename together using the appropriate separator for your platform ( '/' for most operating systems, '\\' for Windows).

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