3

Python 2.x でimportlibを使用して、インポートされたモジュールのバイトコードをオンザフライで書き換える方法を探しています。つまり、インポート中のコンパイルと実行ステップの間に独自の関数をフックする必要があります。それに加えて、組み込みの機能と同じようにインポート機能が機能することを望みます。

私はすでにimputilでそれを行っていますが、そのライブラリはすべてのケースをカバーしているわけではなく、とにかく非推奨です。

4

1 に答える 1

2

ソースコードを確認したので、モジュールでサブクラス化してオーバーライドimportlibできると思います。PyLoader_bootstrapget_code

class PyLoader:
    ...

    def get_code(self, fullname):
    """Get a code object from source."""
    source_path = self.source_path(fullname)
    if source_path is None:
        message = "a source path must exist to load {0}".format(fullname)
        raise ImportError(message)
    source = self.get_data(source_path)
    # Convert to universal newlines.
    line_endings = b'\n'
    for index, c in enumerate(source):
        if c == ord(b'\n'):
            break
        elif c == ord(b'\r'):
            line_endings = b'\r'
            try:
                if source[index+1] == ord(b'\n'):
                    line_endings += b'\n'
            except IndexError:
                pass
            break
    if line_endings != b'\n':
        source = source.replace(line_endings, b'\n')

    # modified here
    code = compile(source, source_path, 'exec', dont_inherit=True)
    return rewrite_code(code)

私はあなたが何をしているのか知っていると思いますが、どこにでもいるプログラマーに代わって私は言うべきだと信じています:ugh = p

于 2010-09-22T13:03:17.127 に答える