参考讨论“比较密钥后将内容从一个YAML复制到另一个YAML”(Copy content from one YAML to another YAML after comparison of keys)
如果不使用ruamel.yaml模块,有没有办法做到这一点。由于我使用的是Python 2.7.5,因此该模块不可用。
#!/usr/local/bin/python2.7.5
import os.path
import yaml
import sys
import ruamel.yaml
面临错误: -
ImportError: No module named ruamel.yaml
谢谢,
答案 0 :(得分:2)
是的,您只需将给定代码更改为import yaml
而不是ruamel.yaml
。您不会有round_trip_load
和round_trip_dump
,但您可以使用safe_load
和safe_dump
。这不会保留评论,因为这是一个茹玛尔特征。
答案 1 :(得分:0)
真正的问题不在于ruamel.yaml不适用于Python 2.7.5,而是环境有问题(实际的Python配置,pip版本,你的平台)。 ruamel.yaml
与2.7.5完美匹配,如下所示:
$ virtualenv -p /opt/python/2.7.5/bin/python /tmp/so_47987860
Running virtualenv with interpreter /opt/python/2.7.5/bin/python
New python executable in /tmp/so_47987860/bin/python
Installing setuptools, pip, wheel...done.
$ source /tmp/so_47987860/bin/activate
(so_47987860) $ python --version
Python 2.7.5
(so_47987860) $ pip --version
pip 9.0.1 from /tmp/so_47987860/lib/python2.7/site-packages (python 2.7)
(so_47987860) $ pip install ruamel.yaml
Collecting ruamel.yaml
/tmp/so_47987860/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/tmp/so_47987860/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Downloading ruamel.yaml-0.15.35-cp27-cp27mu-manylinux1_x86_64.whl (534kB)
100% |████████████████████████████████| 542kB 1.5MB/s
Collecting ruamel.ordereddict; platform_python_implementation == "CPython" and python_version <= "2.7" (from ruamel.yaml)
Using cached ruamel.ordereddict-0.4.13-cp27-cp27mu-manylinux1_x86_64.whl
Installing collected packages: ruamel.ordereddict, ruamel.yaml
Successfully installed ruamel.ordereddict-0.4.13 ruamel.yaml-0.15.35
(so_47987860) $ python
Python 2.7.5 (default, Dec 29 2017, 09:46:55)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ruamel.yaml
>>> yaml = ruamel.yaml.YAML()
>>> import sys
>>> yaml.dump(dict(working_normal='2.7.5'), sys.stdout)
working_normal: 2.7.5
>>> exit()
(so_47987860) $ deactivate
$
由于您使用的是过时版本的Python,因此应检查是否未使用过时版本的pip
。已知旧版本的pip
会导致问题。