I need to embed Python code into a YAML document. The document should preferably be portable (standard YAML), or at least parsable by Python (using PyYaml for example).
In fact I'm trying to include unmodified strings into yaml attributes. Indentations and new lines should be kept, so that embedded Python code could then be executed later.
I found the '>' but it removes newlines.
It is also possible to embed Python in a C++ program; precisely how this is done will depend on the details of the C++ system used; in general you will need to write the main program in C++, and use the C++ compiler to compile and link your program. There is no need to recompile Python itself using C++.
Write YAML File In PythonOpen config.py and add the following lines of code just below the read_yaml method and above the main block of the file. In the write_yaml method, we open a file called toyaml. yml in write mode and use the YAML packages' dump method to write the YAML document to the file.
However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.
You can use the literal scalar block style, introduced with |
. For instance:
code: | def foo(): print "foo" # we can include blank lines with no difficulty foo()
If you need to generate the file from code, then the yaml
module does have functionality that allows you to control the block style: Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?
Thanks to @delnan for pointing me towards this very useful information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With