tags:

views:

44

answers:

3

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
is it possible to copy the module if the module has been loaded, but the file for that module has been deleted?
Bobby Chopra
Doesn't work? `import itertools; print itertools.__file__` gets `AttributeError: 'module' object has no attribute '__file__`
Nas Banov
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
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
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
@Bobby, no, there is no way to recover from the deletion mistake in this fashion.
Alex Martelli
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