pyYAML is dumping a long string over multiple lines. I want the output to be like this -
include:
- interface Vlan6[\s]+vrrpv3 1 address-family ipv4[\s]+address 5.2.1.1 primary[\s]+interface Vlan7[\s]+vrrpv3 1 address-family ipv4[\s]+address 5.2.1.2
However the dump output in the file is coming like this -
include:
- interface Vlan6[\s]+vrrpv3 1 address-family ipv4[\s]+address 5.2.1.1
primary[\s]+interface Vlan7[\s]+vrrpv3 1 address-family ipv4[\s]+address
5.2.1.2
Even came across a link about resolving this using SafeDumper, but I am using another custom dumper to dump into a file for a different use case (fixing indentation). Here is the code -
# MyDumper Class: To correct the indentation of list items
# https://stackoverflow.com/questions/25108581/python-yaml-dump-bad-indentation
class MyDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(MyDumper, self).increase_indent(flow, False)
# Use str for python3 and unicode for lower versions
# https://stackoverflow.com/questions/6432605/any-yaml-libraries-in-python-that-support-dumping-of-long-strings-as-block-liter
class literal_unicode(str): pass
def literal_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal_unicode, literal_unicode_representer)
# save_verify_target -> configure -> commands
key1 = 'interface Vlan6\nvrrpv3 1 address-family ipv4\naddress 5.2.1.1 primary\ninterface vlan 7\nvrrpv3 1 address-family ipv4\naddress 5.2.1.2\n'
# save_verify_target -> execute -> commands
key2 = 'show file vrrp.cfg'
verify_target_str = 'interface Vlan6[\s]+vrrpv3 1 address-family ipv4[\s]+address 5.2.1.1 primary[\s]+interface Vlan7[\s]+vrrpv3 1 address-family ipv4[\s]+address 5.2.1.2'
dict_file = {
'extends': 'common_trigger.yaml',
'setup_device': {
'description': 'Setup device',
'source': {
'pkg': 'libs.sdk'
},
'groups': ['all', 'custom']
},
'Test01': {
'description': 'ID:TC01',
'source': {
'pkg': 'libs.sdk'
},
'groups': ['all', 'custom'],
'test_sections': [
'%{ triggers.pre_config }',
{'save_verify_target': [
{'configure': {
'custom_start_step_message': 'Save target config to a file',
'device': 'uut1',
'command': literal_unicode(key1)
}},
{'execute': {
'custom_start_step_message': 'Verify the target file contents',
'device': 'uut1',
'command': literal_unicode(key2),
'include': [verify_target_str]
}}
]}
]
}
}
with open(r'check.yaml', 'w') as file:
documents = yaml.dump(dict_file, file, sort_keys=False, Dumper=MyDumper, default_flow_style=False)
Here 'verify_target_str' which is a value for key 'include' is a very long string and I want it to come in one single line in the final YAML file i.e. check.yaml.
Can someone please help?