Search code examples
pythonpython-3.xpython-3.4smtplib

access file's actual code as string Python


this is mainly curiosity, I'd like to access my script's actual code, so for a file:

#!/usr/bin/env python
# coding: utf-8

import os, sys, subprocess, time, re
import yagmail

it would return

code = """\
#!/usr/bin/env python
# coding: utf-8

import os, sys, subprocess, time, re
import yagmail"""

I see nice things like file, name, etc, but no code:

__IPYTHON__        __IPYTHON__active  __debug__          __doc__            __file__           __import__         __name__           __package__        
ipdb> 

Thank you


Solution

  • The inspect library has some methods for this (specifically inspect.getsource()).

    https://docs.python.org/3.4/library/inspect.html#retrieving-source-code