[Tutor] Converting code to string
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 23 23:06:14 CEST 2007
"Bernard Lebel" <3dbernard at gmail.com> wrote
> I'm looking for a way to convert Python code into a string.
Read the file as text?
You can find the file by checking the __file__ attribute
of a module.
> Now in the same module, I'd like to take this function and convert
> it
> into a string:
If its the same file then you implicitly know the name of the file,
so long as nobody renames it.
> """def myFunc():
> print 'hello world'\n"""
########### foo.py #########
def f(x): print g(x)
src = open('foo.py').read()
if __name__ == "__main__": print src
############################
There are fancier tricks you could use but for simple things that
might work? Depends on what exactly you need it for.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list