Here is my directory structure:
In file keyword.py I import lottery.lottery at the first line like this:
from lottery.lotterya import Lottery
In file rule.py I import lottery.keyword dynamically like this:
__import('lottery.keyword') but it reports an error "No module named lotterya".
I don't know what to do. Can anyone help?
I dynamically import a module
Here is one solution for your question. It uses importlib to do dynamic import.
In ruly.py
import importlib
if __name__ == '__main__':
mKey = importlib.import_module('lottery.keyword')
MyKeyword = getattr(mKey,'MyKeyword')
k = MyKeyword()
k.mPrint()
In keyword.py
from lottery.lotterya import Lotterya
class MyKeyword():
def __init__(self):
pass
def mPrint(self):
print 'Hello, keyword'
l = Lotterya()
l.lPrint()
In lotterya.py
class Lotterya:
def __init__(self):
pass
def lPrint(self):
print 'Hello, Lotterya'
Related
Im at a mental block of how I can import my python class currently saved as Scrapese.py.
import scrapy
class Scrapese(scrapy.Spider):
name = 'scrape-se'
seach_engine = [
'se1.com',
'se2.com',
]
def parse(self, seach_engine, site_to_parse, page_start, page_end, response):
site = str(seach_engine+site_to_parse)
if site_to_parse == seach_engine[0]:
print("executing against se1!")
elif site_to_parse == searh_engine[1]:
print("executing against se2!")
else:
print("Something bad happened.")
I keep trying to typical:
from Scrapese import parse
but it says:
ImportError: cannot import name 'parse'
What am I doing wrong?
Thanks
Scrapese is the name of a Python module in which you define a class also called Scrapese.
The line from Scrapese import parse will cause the Python interpreter to try importing a module called Scrapese and looking in that for an object parse.
What you probably want to do is the following:
# Scrapese.py
class Scrapese(object):
def parse(self):
pass
# main.py
from Scrapese import Scrapese
o = Scrapese()
o.parse()
This will cause the Python interpreter to make the Scrapese class definition available within another script (main.py), which you can then instantiate and use for parsing.
I'm a newbie in using Python.
What I need is simple: import a module dynamically.
Here is my little test:
#module
class Test:
def func(self, id, name):
print("Your ID: " + str(id) + ". Your name: " + name)
return
I put this class in a file named my_module.py and the path of the file is: c:\doc\my_module.py.
Now I create a new python project to import the file above.
Here is what I do:
import sys
module = sys.path.append(r'c:\doc\my_module.py')
myClass = module.__class__
print(myClass)
However, I got this result:
<class 'NoneType'>
Why can't I get Test?
Is it because the way to import a module is wrong or because I need to do some config to import a module?
You're doing it wrong. Here's how you should import your module with sys.path.append:
import sys # import sys
sys.path.append(r'c:\doc\') # add your module path to ``sys.path``
import my_module # now import your module using filename without .py extension
myClass = my_module.Test # this is how you use the ``Test`` class form your module
try this:
import sys
sys.path.append(r'c:\doc\') # make sure python find your module
import my_module # import your module
t = my_module.Test() # Initialize the Test class
t.func(1, 'test') # call the method
The way to import a module is through the import command. You can specify the path with sys as a directory. You also need to instantiate the class within the module (through the my_module.Test()). See the following:
import sys
sys.path.append(r'c:\doc\\')
import my_module
myObj = my_module.Test()
myClass = myObj.__class__
print(myClass)
I followed advice here on stackoverflow on how to import a class
from a path outside of the root folder:
How to dynamically load a Python class
Does python have an equivalent to Java Class.forName()?
Unfortunately this raises the error:
ValueError: Empty module name
It is my understanding that import should not return an empty module, like the load_source method from imp. So I do not understand this error nor how to approach it.
What am I implementing wrong here?
Could you tilt me into the right direction here?
Thanks!
Code:
klass = __import__('..folder.module.Class_A')
some_object = klass()
class class_B(some_object):
def run(self):
print ('Test OK!')
Imported class (content of module):
class Class_A():
def __init__(self, arg1, *args):
def run(self):
pass
First of all you are not using import correctly.
Option 1:
According to https://docs.python.org/2/library/functions.html#import you should be doing:
klass = __import__('folder.module', globals(), locals(), ['Class_A'], -1)
Now if you want Class_A itself you should do:
some_object = klass.Class_A
Then you can inherit from it using:
class class_B(some_object):
def run(self):
print ('Test OK!')
Option 2:
from folder.module import Class_A
Then you can inherit from it using:
class class_B(Class_A):
def run(self):
print ('Test OK!')
Note: In folder.module folder should be a python package and module should be a python module
Either it's lack of sleep but I feel silly that I can't get this. I have a plugin, I see it get loaded but I can't instantiate it in my main file:
from transformers.FOMIBaseClass import find_plugins, register
find_plugins()
Here's my FOMIBaseClass:
from PluginBase import MountPoint
import sys
import os
class FOMIBaseClass(object):
__metaclass__ = MountPoint
def __init__(self):
pass
def init_plugins(self):
pass
def find_plugins():
plugin_dir = os.path.dirname(os.path.realpath(__file__))
plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith("Transformer.py")]
sys.path.insert(0, plugin_dir)
for plugin in plugin_files:
mod = __import__(plugin)
Here's my MountPoint:
class MountPoint(type):
def __init__(cls,name,bases,attrs):
if not hasattr(cls,'plugins'):
cls.plugins = []
else:
cls.plugins.append(cls)
I see it being loaded:
# /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.pyc matches /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.py
import SctyDistTransformer # precompiled from /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.pyc
But, for the life of me, I can't instantiate the 'SctyDistTransformer' module from the main file. I know I'm missing something trivial. Basically, I want to employ a class loading plugin.
To dymically load Python modules from arbitrary folders use imp module:
http://docs.python.org/library/imp.html
Specifically the code should look like:
mod = imp.load_source("MyModule", "MyModule.py")
clz = getattr(mod, "MyClassName")
Also if you are building serious plug-in architecture I recommend using Python eggs and entry points:
http://wiki.pylonshq.com/display/pylonscookbook/Using+Entry+Points+to+Write+Plugins
https://github.com/miohtama/vvv/blob/master/vvv/main.py#L104
Say I have a package "mylibrary".
I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.
I.e., I do:
import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
Given that setup:
>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
Even stranger:
>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?
You need to monkey-patch the module not only into sys.modules, but also into its parent module:
>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)>
As well as the following:
import sys, types
config = types.ModuleType('config')
sys.modules['mylibrary.config'] = config
You also need to do:
import mylibrary
mylibrary.config = config
You can try something like this:
class VirtualModule(object):
def __init__(self, modname, subModules):
try:
import sys
self._mod = __import__(modname)
sys.modules[modname] = self
__import__(modname)
self._modname = modname
self._subModules = subModules
except ImportError, err:
pass # please signal error in some useful way :-)
def __repr__(self):
return "Virtual module for " + self._modname
def __getattr__(self, attrname):
if attrname in self._subModules.keys():
import sys
__import__(self._subModules[attrname])
return sys.modules[self._subModules[attrname]]
else:
return self._mod.__dict__[attrname]
VirtualModule('mylibrary', {'config': 'actual_module_for_config'})
import mylibrary
mylibrary.config
mylibrary.some_function