is there a function like this ?
change_directory_func = from_import("chdir", "os")
Python3x, from_import(name, from) function
|
is there a function like this ?
change_directory_func = from_import("chdir", "os")
You could do something like
chdir = getattr(__import__('os'), 'chdir')But why would you want to?
May-12-2017, 08:43 PM
You could also do "from xxx import yyy", with an "as" alias:
from os import chdir as change_directory_func
May-12-2017, 08:57 PM
my code
i solved problem with exec. exec("from .langpacks import {}\n" "langmodule = {}\n" "del {}".format(name, name, name) )
May-12-2017, 09:36 PM
Where does
name come from? If it's untrusted, you'll be evaluating real code, so someone could do something likename = """whatever import os os.system("rm -rf /") """NOTE you shouldn't run the code I have above, it will do irrepairable damage to most systems.
my full code
# __init__.py import os __directory__ = os.path.dirname(__file__) __langpacksdir__ = __directory__ + "/" + "langpacks" # this dict is not a langpack only contains system language packs so this dict musn't be translated ! LANGPACKS = { "_val": "This PACK Contains Language Packs", "_info": "LANGPACKS of language module of RcD 1.0 Created by Lorderon", "_lang_count": 0, # this "_langpacks": [] } LANGMODULES = {} ignoredfolders = ("__pycache__",) for name in os.listdir(__langpacksdir__): if os.path.isfile(__directory__ + "/" + name) or name in ignoredfolders: continue try: exec("from .langpacks import {}\n" "langmodule = {}\n" "del {}".format(name, name, name) ) langpack = langmodule.PACK langid = langpack["_lang_id"] if langpack["_pack_type"] != "langpack": raise Exception except: # from traceback import print_exc; print_exc() continue if langid in LANGMODULES: continue LANGMODULES[langid] = langmodule LANGPACKS[langid] = langpack LANGPACKS["_langpacks"].append(langid) LANGPACKS["_lang_count"] += 1 del langpack, langmodule, langid, namei can't find another way than exec func to do this. because load_soruce func from imp module is deprecated in python3x and i didn't do that with antoher modules' func (importlib) ): i love load_source <3
May-13-2017, 09:57 AM
Several months ago I had a similar problem - dynamic import in Python3. This is my solution - luckily, I've preserved it
def dynamic_import(module_name, path2module): """ Dynamic import of module :param module_name: name of module :param path2module: path to module :return: module object """ dynamic_spec = imp_util.spec_from_file_location( module_name, '{}/{}.py'.format(path2module, module_name)) dynamic_module = imp_util.module_from_spec(dynamic_spec) dynamic_spec.loader.exec_module(dynamic_module) return dynamic_module
Test everything in a Python shell (iPython, Azure Notebook, etc.)
|
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Python3x running only with one instance (how can I prevent too many running instance) | harun2525 | 5 | 21,057 |
Jul-21-2017, 07:36 PM Last Post: nilamo |