dynamic-import

Dynamically import a method in a file, from a string

倾然丶 夕夏残阳落幕 提交于 2019-11-26 15:22:27
问题 I have a string, say: abc.def.ghi.jkl.myfile.mymethod . How do I dynamically import mymethod ? Here is how I went about it: def get_method_from_file(full_path): if len(full_path) == 1: return map(__import__,[full_path[0]])[0] return getattr(get_method_from_file(full_path[:-1]),full_path[-1]) if __name__=='__main__': print get_method_from_file('abc.def.ghi.jkl.myfile.mymethod'.split('.')) I am wondering if the importing individual modules is required at all. Edit: I am using Python version 2.6

Dynamically importing Python module

让人想犯罪 __ 提交于 2019-11-26 06:39:31
问题 I have a trusted remote server that stores many custom Python modules. I can fetch them via HTTP (e.g. using urllib2.urlopen ) as text/plain, but I cannot save the fetched module code to the local hard disk. How can I import the code as a fully operable Python module, including its global variables and imports? I suppose I have to use some combination of exec and imp module\'s functions, but I\'ve been unable to make it work yet. 回答1: It looks like this should do the trick: importing a