yaml 八进制整数生成错误

yaml octal integer generate errors

在我的 YAML 文件中有以下条目:

- type: dir
  name: .ssh
  chmod: 0o700

根据YAML 1.2 specification 3.2.1.3 节,0o700 是指定八进制数的方法(2.4 节中也有示例)

然而,当我处理加载的文件并执行以下操作时:

import os
import yaml
filename = "in.yml"

with open(filename) as fp:
    for e in yaml.load(open(filename)):
        if e['type'] == 'dir':
            os.mkdir(e['name'], e['chmod'])

我得到 TypeError: an integer is required。这里出了什么问题?

我正在使用 Python 3.5

错误的是您假设您的 YAML 库支持最新版本 1.2。该 YAML 版本来自 2009 年,但您使用的是 PyYaml,它仍然只支持 1.1。从非activity最近几年来看,它似乎是一个死项目,所以不要指望这个问题很快就会得到解决。

您可以添加

from yaml.resolver import Resolver

Resolver.add_implicit_resolver(
    'tag:yaml.org,2002:int',
    re.compile(r'''^(?:[-+]?0b[0-1_]+
               |[-+]?0o?[0-7_]+
               |[-+]?0[0-7_]+
               |[-+]?(?:0|[1-9][0-9_]*)
               |[-+]?0x[0-9a-fA-F_]+
               |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
    list('-+0123456789'))

在您的程序中添加对 0o123 有点八进制的识别(它仍然可以识别 1.1 八进制)。

请注意上面的 适用于 Python 3,因为 PyYaml 对 Python 2.

有不同的代码

您还应该考虑使用 pathlib.Path 类型及其 .mkdir() 而不是 os.mkdir()

安装ruamel.yaml ( pip install ruamel.yaml ). It defaults to loading 1.2 as documented here:

unless the YAML document is loaded with an explicit version==1.1 or the document starts with:

% YAML 1.1

, ruamel.yaml will load the document as version 1.2.

YAML 1.2 no longer accepts strings that start with a 0 and solely consist of number characters as octal, you need to specify such strings with 0o[0-7]+ (zero + lower-case o for octal + one or more octal characters).