tschm tschm - 1 year ago 77
Python Question

Converting the *.py script into a string

I run a bunch of scripts and typically I store their outcome in a MongoDB. To make sure I can link the results with the input script I store the entire script as text. This works beautifully in Python 3 using the following code fragment:

module = importlib.import_module(module)
with open(module.__file__) as ff:
source = ff.read()

Applying the same trick in Python 2 results in a mess. Initially the variable module is a string such a.b.foo. Unfortunately I can not abolish Python 2 yet.

Answer Source

In many cases you do not get the *.py file with __file__ but instead the *.pyc file. Which in your case is indeed a mess. Just cut off the last character of the filename ;)

import os
import importlib

#new_module = __import__("module")
new_module = importlib.import_module("module")

new_module_filename = os.path.realpath(new_module.__file__)
if new_module_filename.endswith(".pyc"):
    new_module_filename = new_module_filename[:-1]

with open(new_module_filename) as ff:
    source = ff.read()