Python Forum

Full Version: How to get a module's code as string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I'm coding to the cloud, so I'm stuck in a situation in which I want to know what is written inside a module, but I dont have the permission to view it (I do have the permission to import it).
It's a unique module (written by the creators of the site), so it's impossible to find it be simply googling it's name.
Can I somehow get the module's code as python string?
you can use inspect.getsource()

metulburr@ubuntu:~$ echo "class Klass:pass" >> module_imported.py
metulburr@ubuntu:~$ cat module_imported.py 
class Klass:pass
example file is created

metulburr@ubuntu:~$ python3
Python 3.6.1 (default, Jun  8 2017, 06:36:16) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import module_imported as mi
>>> import inspect
>>> inspect.getsourcelines(mi)
(['class Klass:pass\n'], 0)
>>> inspect.getsource(mi)
'class Klass:pass\n'