Python Forum
How to get a module's code as string
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get a module's code as string
#1
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?
Reply
#2
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'
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  trouble reading string/module from excel as a list popular_dog 0 417 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,549 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  How to run code again in module ? rajamani 2 896 Nov-10-2022, 02:38 PM
Last Post: snippsat
  AttributeError: module 'string' has no attribute 'uppercase' Anldra12 10 10,261 Apr-23-2021, 05:30 PM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020