[英]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.