简体   繁体   English

Python软件包:我可以从调用它的项目目录中查找config / yml文件吗?

[英]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. 我正在编写一个Python包,其中包含一堆特定于我们团队的实用程序类型的函数,以便它们可以安装,导入和使用它们。 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. 其中一些功能访问需要身份验证的服务,因此我在READ Me文件中指示它们在其项目目录中创建一个包含其凭据的YAML文件。

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? 当他们导入此程序包并从中调用函数时,程序包是否有办法在调用它的目录中查找此YAML文件? 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. __file__变量包含Python程序的名称或路径。 We can use functions from the os.path submodule to use this to get a file (in my example below called password.yml ). 我们可以使用os.path子模块中的函数来获取文件(在我的示例中称为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). abspath将名称转换为绝对文件(从文件系统根目录开始)。 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). dirname删除最后一个(文件名)组件,保留目录,并使用适合您平台的分隔符(对于大多数操作系统为'/' ,对于Windows为'\\' ), join将目录路径和文件名放在一起。

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

相关问题 Python yml 配置文件 - Python yml config file 我们如何从 python 中的嵌套目录创建配置文件? - how can we create a config file from a nested directory in python? 如何运行从 Github 下载的 python 项目(有很多带有 .py 的文件)? - How can I run a python project (has many file with .py) which downloaded from Github? 如何从不同目录正确运行 python 项目 - How can I run properly python project from different directory 在python DEAP软件包中,为什么可以从不具有此功能的模块中调用该功能? - In python DEAP package, why a function can be called from a module which dose not have such function? 无法从另一个目录导入文件,该目录从同一目录导入文件(int Python) - Can't import file from another directory which imports a file from the same directory (int Python) 如何从`src/`目录下的python包访问项目根目录中的文本文件 - How to access text file in project root from python package under `src/` directory 将文件从Python包导入到目录中 - Importing a file from a Python package in to a directory 如何获取正在调用 python 可执行文件的目录? - How to get the directory from which a python executable is being called? 如何从 yml 文件执行 python 代码? - How do I execute python code from yml file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM