简体   繁体   中英

Importing a python module into a dict (for use as globals in execfile())?

I'm using the Python execfile() function as a simple-but-flexible way of handling configuration files -- basically, the idea is:

# Evaluate the 'filename' file into the dictionary 'foo'.
foo = {}
execfile(filename, foo)

# Process all 'Bar' items in the dictionary.
for item in foo:
  if isinstance(item, Bar):
    # process item

This requires that my configuration file has access to the definition of the Bar class. In this simple example, that's trivial; we can just define foo = {'Bar' : Bar} rather than an empty dict. However, in the real example, I have an entire module I want to load. One obvious syntax for that is:

foo = {}
eval('from BarModule import *', foo)
execfile(filename, foo)

However, I've already imported BarModule in my top-level file, so it seems like I should be able to just directly define foo as the set of things defined by BarModule , without having to go through this chain of eval and import .

Is there a simple idiomatic way to do that?

Maybe you can use the __dict__ defined by the module.

>>> import os
>>> str = 'getcwd()'
>>> eval(str,os.__dict__)

使用内置的vars()函数以dict的形式获取对象(例如模块)的属性。

The typical solution is to use getattr:

>>> s = 'getcwd'
>>> getattr(os, s)()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM