In Python, how can I access the namespace of the main module from an imported module?
Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how开发者_开发技巧 to go in the other direction.
import __main__
But don't do this.
The answer you're looking for is:
import __main__
main_global1= __main__.global1
However, whenever a module module1
needs stuff from the __main__
module, then:
- either the
__main__
module should provide all necessary data as parameters to amodule1
function/class, - or you should put everything that needs to be shared in another module, and import it as
import module2
in both__main__
andmodule1
.
I think this would work:
import sys
main_mod = sys.modules['__main__']
Not sure if it is a good practice but maybe you could pass the objects and variables you need as parameters to the methods or classes you call in the imported module.
精彩评论