定义软链接时,从Python引用YAML配置文件 [英] Referencing a YAML config file, from Python, when a softlink is defined

查看:222
本文介绍了定义软链接时,从Python引用YAML配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码;

#!/usr/bin/env python3

import yaml

with open('config.yml', 'r') as config_file:
    config = yaml.load(config_file)

文件名为 __ init __。py ,位于目录〜/ bin / myprogram / myprogram / ,在同一目录中,我有一个名为 config.yml

The file is called __init__.py which is in the directory ~/bin/myprogram/myprogram/ and in the same directory, I have a file called config.yml

我的符号链接如下;

user$ ls -la /usr/local/bin/

lrwxr-xr-x    1 user  admin        55 27 Nov 13:25 myprogram -> /Users/user/bin/myprogram/myprogram/__init__.py

每次运行myprogram时,我得到错误 FileNotFoundError:[错误2]没有这样的文件或目录:'config.yml'。我相信这是因为 config.yml 不在 / usr / local / bin / 中。解决此问题的最佳方法是什么?

Every time I run myprogram, I get the error FileNotFoundError: [Errno 2] No such file or directory: 'config.yml'. I believe this is because the config.yml is not in /usr/local/bin/. What is the best way to work around this issue?

推荐答案

您可以使用 __ file __ 在文件中执行代码时访问 __ init __。py 文件的位置。它返回完整路径,但必须小心,因为它可能是 .pyc (或 .pyo )版。由于您使用的是Python3,因此我将使用pathlib模块:

You can use __file__ to access the location of the __init__.py file when executing code in that file. It returns the full path, but care has to be taken as it may be the .pyc (or .pyo) version. Since you are using Python3 I would use the pathlib module:

import yaml
from pathlib import Path

my_path = Path(__file__).resolve()  # resolve to get rid of any symlinks
config_path = my_path.parent / 'config.yaml'

with config_path.open() as config_file:
    config = yaml.safe_load(config_file)

请注意:


  • 如果必须使用PyYAML,请使用 safe_load(),即使PyYAML自己的文档也指出 .load( )是不安全的。几乎从来没有必要使用它。并且在不太可能的情况下, safe_load()无法加载您的配置,例如如果它具有 !! python /...标记,则应将注册所需的类显式添加到 SafeLoader )。

  • If you have to use PyYAML, use safe_load(), even PyYAML's own documentation indicates .load() can be unsafe. It almost never necessary to use that. And in the unlikely event that safe_load() cannot load your config, e.g. if it has !!python/... tags, you should explicitly add register the classes that you actually need to the SafeLoader).

由于 2006年9月 推荐的YAML扩展名文件 .yaml

这篇关于定义软链接时,从Python引用YAML配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆