I ran the Python REPL tool and imported a Python Module. Can I can dump the contents of that Module into a file? Is this possible? Thanks in advance.
+1
A:
In what format do you want to write the file? If you want exactly the same format that got imported, that's not hard -- but basically it's done with a file-to-file copy. For example, if the module in question is called blah
, you can do:
>>> import shutil
>>> shutil.copy(blah.__file__, '/tmp/blahblah.pyc')
Alex Martelli
2010-07-22 23:47:51
is it possible to copy the module if the module has been loaded, but the file for that module has been deleted?
Bobby Chopra
2010-07-23 01:57:36
Doesn't work? `import itertools; print itertools.__file__` gets `AttributeError: 'module' object has no attribute '__file__`
Nas Banov
2010-07-23 02:19:53
This works only for modules that do exist as a file (source or bytecode); if the file has never existed as such (but rather only as machine code living in a dynamic library, or as machine code linked into Python's executable) or has been deleted after loading, there is no way to create (or re-create) the file "from scratch" based on memory contents.
Alex Martelli
2010-07-23 05:26:27
A:
Do you mean something like this?
http://www.datamech.com/devan/trypython/trypython.py
I don't think it is possible, as this is a very restricted environment.
The __file__
attribute is faked, so doesn't map to a real file
gnibbler
2010-07-23 01:53:28
I am running the repl on my machine's console. After loading the module, I deleted the module's directory. Is there a way to get to copy the module's contents, without the physical file?
Bobby Chopra
2010-07-23 02:06:23
@Bobby, no, there is no way to recover from the deletion mistake in this fashion.
Alex Martelli
2010-07-23 05:27:02
A:
You might get a start by getting a reference to your module object:
modobject = __import__("modulename")
Unfortunately those aren't pickleable. You might be able to iterate over dir(modobject)
and get some good info out catching errors along the way... or is a string representation of dir(modobject)
itself what you want?
altie
2010-07-23 02:19:19