Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed Python code into YAML?

Tags:

python

yaml

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.

like image 993
user2245644 Avatar asked Jan 19 '14 16:01

user2245644


People also ask

Can you embed Python?

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++.

How do you write to a YAML file in Python?

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.

Does Python have built in YAML?

However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.


1 Answers

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.

like image 103
David Heffernan Avatar answered Nov 15 '22 10:11

David Heffernan