Is it possible to store data in a Python file in a way similar to Ruby's __END__ section?

Stephen Hansen apt.shansen at gmail.invalid
Fri Apr 2 16:52:25 EDT 2010


On 2010-04-02 13:08:00 -0700, Christopher Roach said:

> I have a script that I am working on to process a bunch of data. A
> good portion of the Tk-based GUI is driven by a large set of YAML data
> and I'd love to store that data inside of the script so that I can
> send just a single file to my colleague. Ruby has a mechanism for
> doing this whereby I can load the data by doing a YAML.load(DATA)
> which loads everything in the file after the __END__ keyword (for a
> better explanation of this see http://bit.ly/V9w8m). I was wondering
> if anyone knew of a way to do something similar in Python?

If its just like a YAML file or such, the idiomatic thing to do is just 
use a triple-quoted string, I think.

Such as:

DATA="""
My stuff
and stuff
and more stuff
and other stuff"""

If you're wanting to include binary stuff like images, that gets more 
complicated. I've seen it done a couple different ways, but usually 
storing as above but base64 encoding the strings first.

Anything more, and its usually time to start packaging the thing wiht 
py2exe or similar things :)

Now, one concern you may have is order-- you may not want this stuff on 
top of your script, but instead on the bottom so its sort of 'out of 
the way'. For that, I'd do like:

import YAML

def random_thing(arg):
    return arg + 1

def main():
    config = YAML.load(DATA)

# Code ends

DATA="""
blah blah
blah"""

# Bootstrap

if __name__ == "__main__":
    main()

-- 
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.




More information about the Python-list mailing list