I'm trying to write a Python program that registers multiple importable modules while still being a single file.
I have a simple python program called import_module ... it's intended to define a module called foo whose implementation resides in a string literal.
In the example below, compile is called before foo is imported, but the compiled code object is simply discarded. What do I need to do in order to associate it to the name foo so that import foo will work?
#! /usr/bin/env python
compile(
'''
def hello():
print("hello")
''',
'foo',
'exec'
)
import foo
foo.hello()
When run, this program produces the error:
./import_module
Traceback (most recent call last):
File "./import_module", line 12, in <module>
import foo
ImportError: No module named foo
Exit 1
I'd like it to print hello, but am not sure what to do with the code object to register it with the import system.
Ideally, I'd like to do this in such a way that it works independently of version. I'm trying to write a single script that can be run on systems where python is either python2 or 3+.
If no such version independent-method of registering modules exists, I'm okay with inspecting the version info and doing something different depending on the version.