![](/img/trans.png)
[英]When using this loop, I'm not getting the results I want and I'm not sure how to get the code to work on Python
[英]I'm not getting the exact output i want using python
我無法獲得所需的輸出。 嘗試了格式化字符串等基本方法,但仍然沒有得到我想要的輸出。
from pathlib import Path
eth_file = Path("/etc/netplan/01-network-manager-all.yaml")
yml = ruamel.yaml.YAML()
data = yml.load(eth_file)
eth = input("Enter interface name \n")
addr = input("Enter IP address and mask. e.g., 8.8.8.8/8 \n")
dns = input("Enter DNS \n")
rts = input("Enter routes -to \n")
rts1 = input("Enter routes via \n")
new_ether = {eth: dict(
addresses=[addr],
nameservers=dict(addresses=f"[{dns}]"),
routes=[dict(to=rts, via=rts1)]
)}
data['network']['ethernets'].update(new_ether)
yml.dump(data, eth_file)
我得到的輸出是這樣的:
addresses:
- ''
nameservers:
addresses: '[2.34]'
routes:
- to: ''
via: ''
但我不希望名稱服務器地址字段用引號括起來,例如 - '[xx]' 。 我希望這個字段放在沒有任何逗號的簡單方括號中,例如 - [xx] 。
addresses: '[2.34]'
How I want it looks
nameservers:
addresses: [2.34] #without any inverted commas
如果您加載此 YAML:
nameservers:
addresses: [2.34]
您將獲得一個數據結構,其根部具有類 dict 並作為(唯一)根級鍵的值。 關鍵addresses
的值是一個由單個浮點數組成的列表(並且它是流式的)。 如果您有問題,您應該始終嘗試加載您想要實現的 YAML,然后對其進行分析,並將其轉儲回 YAML(查看它是否更改)。
由於[
和]
在 YAML 中具有特殊含義,因此您當然不能將前者放在純標量字符串的開頭。 如果你把它作為字符串輸入,你會得到報價。
# coding: utf-8
import sys
import ruamel.yaml
def flow_seq(*x):
ret_val = ruamel.yaml.CommentedSeq(x)
ret_val.fa.set_flow_style()
return ret_val
yaml = ruamel.yaml.YAML()
data = dict(nameservers=dict(addresses=flow_seq(2.34)))
yaml.dump(data, sys.stdout)
這使:
nameservers:
addresses: [2.34]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.