I've made a Python application which can load plugins. These plugins are loaded based on a name and path.
I am currently using
pluginModule = imp.load_source(pluginModuleName, pluginModulePath)
and then getting a class instance in the module this way
# Load the module class and initialize it.
if hasattr(pluginModule, pluginClassName):
try:
pluginClassInst = getattr(pluginModule, pluginClassName)()
except Exception as e:
errorMsg = ('In plugin module [{}], {}'.format(os.path.basename(pluginModulePath), e))
exceptionTracePrint(self._log)
self._log.error(errorMsg)
continue
Since the imp lib is deprecated I want to use importlib. And the only similar method of getting my class instance was to use
pluginModule = importlib.machinery.SourceFileLoader(pluginModuleName, pluginModulePath).load_module()
The weird thing here is that (I am using pyCharm as IDE). when I run my code in debugging mode the above command works fine and I get my class instance. however running the code normally gives me the following error.
pluginModule = importlib.machinery.SourceFileLoader(pluginModuleName, pluginModulePath).load_module()
AttributeError: 'module' object has no attribute 'machinery'
Why is there a difference between run and debug.
Is there an alternative way of doing what I want.
Ive also tried
pluginModuleTmp = importlib.util.spec_from_file_location(pluginModuleName, pluginModulePath)
Which also gives me the correct data however I cannot load the module this way or at least I do not know how
Regards
Anders
Found the solution. Apparently in debug mode a lot more modules are imported behind my back. I fixed it by adding the import.
import importlib.machinery
Regards
Anders
Related
As the title says I get a "no module named _____" exception when running a script through IronPython. The module that it can't find is warnings. What is strange, however, is that I do not import warnings or use any of its functions in the python script. Warnings is a default class I know, but if that's the case IronPython should have access directly to it right? I tried making a test script with all of the imports I use but the actual code was just hello world and that worked fine. Can I add some path to help IronPython find warnings somehow? If not, why is it throwing this error in this instance?
Here is what I have so far in terms of paths:
var engine = Python.CreateEngine();
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(#"C:\Users\User\source\repos\FileName\bin\Debug\netcoreapp3.1");
searchPaths.Add(#"C:\Users\User\source\repos\PythonScript\PythonScriptFolderLocation");
searchPaths.Add(#"C:\Users\User\source\repos\PythonScript\PythonScriptFolderLocationEnv\Lib");
searchPaths.Add(#"C:\Users\User\source\repos\PythonScript\PythonScriptFolderLocationEnv\Lib\site-packages");
engine.SetSearchPaths(searchPaths);
var script = "C:\\Users\\User\\source\\repos\\PythonScript\\PythonScriptFolderLocation\\run.py";
So I am pretty new with Python. I've been working on running with a code similar to one I hope to build myself (so a reference code). Aside from some bugs I need to work out with invalid syntax, all seems to work except for one issue with one particular .py file I have.
My structure is this:
MoodForecasting -> eval -> nsga_two.py
I do have _init_.py in eval folder though, so I'm not sure why this block of code isn't working.
I am trying to load one particular fucntion from it, so the structure should look like this
from nsga_two import PatientProblem
Unfortunately, I keep getting the error ModuleNotFoundError: No module named 'nsga_two'.
I checked nsga_two.py itself and found that it couldn't load inspyred. I went in and was able to fix this. So, nsga_two.py runs fine on its own. However, I cannot import it into the main script I will be working with.
Some extra details: I am working with the IDE Spyder with Python Custom Version 3.7.9.
I'm not sure if it is an issue with Spyder or just how I am loading in my working directory. (Most of my coding experience is in MatLab and R so having an IDE similar to RStudio and MatLab is the reason I chose to work in Spyder)
Edit:
I got a syntax error when using from eval import nsga_two.PatientProblem. Python didn't like the period. So, I instead tried it with no period. I got the error cannot import name 'nsga_twoPatientProblem' from 'eval' (C:\Users\name\Desktop\MoodForecasting-master\MoodForecasting-master\eval\__init__.py). I don't know why. But doing from eval import nsga_two works. nsga_two.py only consists of PatientProblem. This solve should be ok for this purpose. I'm just not sure why this could be happening.
Suppose your structure is like:
MoodForecasting-master/
main.py
eval/
__init__.py
nsga_two.py
When you run the main script to import something, the directory of that script is added to the module search path sys.path, .../MoodForecasting-master/ in this case. from nsga_two import PatientProblem raised ModuleNotFoundError because nsga_two.py is not in that directory.
As Iguananaut said, from eval import nsga_two.PatientProblem in the first comment has never been a valid statement. The valid ways of doing so are:
import by from eval import nsga_two and use as nsga_two.PatientProblem().
import by from eval.nsga_two import PatientProblem and use as PatientProblem() directly.
Module search starts from .../MoodForecasting-master/, first option go to .../MoodForecasting-master/eval/ to find nsga_two.py, second option go to .../MoodForecasting-master/eval/nsga.py to find attribute named PatientProblem.
The correct syntax would be:
from package.module import function
so:
from eval.nsga_two import PatientProblem
I'm trying to understand the behavior of import in python.
I used del numpy.dtype, and it throws an error when I type numpy.dtype. But when I try to re-inport numpy, it doesn't help.
I tried to follow the answer from Python: "de-import", "re-import", "reset import"? by doing del sys.modules['numpy'], but I get an error when I try to import numpy again afterwards.
The weird part about all of this is that I can still use numpy without any issue, except that when I type numpy.dtype, I get the error:
AttributeError: 'module' object has no attribute 'dtype'
Can someone explain what is happening and how I can restore:
numpy.dtype
the ability to import numpy without error
I'm using Python2.7 in a Spyder interactive IPython console.
A module will only get imported once in Python, so your subsequent imports do nothing. You can use importlib's reload method to reload a library, which will bring dtype back, after you have deleted it.
import importlib
importlib.reload(numpy)
# numpy.dtype accessible again
You mentioned you are using Python 2.7, and the importlib included in 2.7 is mainly for ease of updating, and does not contain a reload method. You should really update to Python 3, as 2020 is approaching fast, but you can use the builtin reload method if you insist.
I first tried with the interpreter to produce uuid's with python's uuid module. I did the following:
>>>import uuid
>>>uuid.uuid1()
UUID('d8904cf8-48ea-11e0-ac43-109add570b60')
So far so good. I create a simple little function to produce the uuid's.
import uuid
def get_guid():
return uuid.uuid1()
if __name__ == '__main__':
print get_guid()
and I get the following error:
AttributeError: 'module' object has no attribute 'uuid1'
Ok...hmm...go back to the interpreter and now it too is broken. I get the same error running the same code I used to test this. I am baffled. What makes uuid break like this? And what is wrong with my code?
I am using python 2.6
Your test file name is most likely named uuid.py
When you went back to the interpreter, you launched the interpreter from the same directory, which by default, will first look for the module name to import in your current working directory.
Just change your test file name to something else, i.e. uuid_test_snippet.py
I have inherited a few Python scripts from someone who has left my employer. Some are meant to be run from Jython, others are not.
I'd like to add them to svn, but before I do I want to modify these files so that if a "requires Jython" file is run from python, the user gets a message like "please run with Jython" and the program exits.
(Warning: I am not very familiar with Python/Jython.)
I expect the simplest way to do this is create a file require-jython.py with the contents like:
if runtime.name != 'jython'
print "Please run with Jython"
exit(1)
and then "include/require"? this file (again I'm not an expert. bear with me here)
Can anyone spell out the steps for me?
What I have seen done is to try to import a module exclusive to a given version or implementation, and raise ImportError if the module does not exist.
Imagine that Jython (and not Python) has a module called special, then you add:
# at the top of your module:
try:
import special
except ImportError:
raise ImportError("this script is meant to be used with Jython")
else:
raise
Notice that you make the ImportError exception more explicit, as opposed to simply raising it (and lead the user to believe that there was a problem with the module itself, as opposed to informing that the interpreter was improperly selected). I would give you a more concrete example of what module to import, but I am not at all familiar with Jython.
In other words, use duck typing for the module import: assume the import was made correctly but fail as soon as you cannot find the expected behaviour (this is what the try statement is supposed to be used for).
Another way to check the interpreter is to use the sys module (in Python - I don't know if Jython has it):
>>> import sys
>>> print sys.subversion
('CPython', 'tags/r264', '75821M')