I have a pure C module for Python and I’d like to be able to invoke it using the python -m modulename approach. This works fine with modules implemented in Python and one obvious workaround is to add an extra file for that purpose. However I really want to keep things to my one single distributed binary and not add a second file just for this workaround.
I don’t care how hacky the solution is.
If you do try to use a C module with -m then you get an error message No code object available for <modulename>.
-mimplementation is inrunpy._run_module_as_main. Its essence is:A compiled module has no “code object” accociated with it so the 1st statement fails with
ImportError("No code object available for <module>"). You need to extend runpy – specifically,_get_module_details– to make it work for a compiled module. I suggest returning a code object constructed from the aforementioned"import mod; mod.main()":(python 2.6.1)
(Update: fixed an error in format string)
Now…
This still won’t work for builtin modules. Again, you’ll need to invent some notion of “main code unit” for them.
Update:
I’ve looked through the internals called from
_get_module_detailsand can say with confidence that they don’t even attempt to retrieve a code object from a module of type other thanimp.PY_SOURCE,imp.PY_COMPILEDorimp.PKG_DIRECTORY. So you have to patch this machinery this way or another for-mto work. Python fails before retrieving anything from your module (it doesn’t even check if the dll is a valid module) so you can’t do anything by building it in a special way.