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
Related
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'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
I have already browsed all the topics close to this but couldn't find the answer to my question.
I have the following directory structure
--Codes
+------mod_welch.py
+------__init__.py
+------Toy_Model
++---------__init__.py
++---------linear_filter.py
Both of __init__.py's are empty and I am trying to access to mod_welch.py in the body of linear_filter.py with no success. When I want to use realtive access to upper folders as
from ..mod_welch import welch where welch is a function inmod_welch I receive:
ValueError: Attempted relative import in non-package
What am I doing wrong?
In genereal, your module should be import-ed somewhere and then used. Error message that you're receiving suggests that there is unusual execution method of module code. I suspect that youre testing your code by runnig python linear_filter.py (it gives the same error). Thats not the way.
As I said above you need to actually use your module if you want to test its functionality. To do that, you can import your module in another module or main script, for example:
from Codes.Toy_Model.linear_filter import some_method
if __name__ == '__main__':
print(some_method())
Where some_method is defined in linear_filter.py as:
from Codes.mod_welch import welch
def some_method()
welch()
If that's not the case then please provide additional information about what is an usage (execution) method of your module -- which script are you running and how. Any sys.path.append magic etc. are important here too.
Maybe I am completely missing something here but when I run this code form the shell it works:
import nltk
tokens = nltk.word_tokenize("foo bar")
and returns:
['foo','bar']
But when I but this into a file and execute it with python -u "path/to/file/myfile.py" it returns
AttributeError: 'module' object has no attribute 'word_tokenize'
I've tried reinstalling and every thing i can think of. Let me know if you need any more information.
Thanks in Advance!
You have more than likely called your file nltk.py so python is trying to import from that as opposed to the actual nltk module. Just rename your .pyfile.
I'm trying to import external modules into my controller code for a web2py application. The module I'm importing is located in myapp/modules and seems to import fine. However, it doesn't let me call any of the functions defined in there; gives the following error
'module' object has no attribute 'testfunc'
I'm importing like this:
import json_utils as u
And calling like this:
u.testfunc()
Am I missing something obvious here? I have tried stop/starting the server in case its not reloaded the file.
Cheers
EDIT: Here is the entire json_utils.py file:
def testfunc():
return 3
def testfunc2():
# some stuff
return 5
Problem is web2py caching external modules. Stop/Starting the server is not enough, I need to kill the whole thing are reboot.
It's saying that json_utils has no function called testfunc
The module json_utils has no built-in function testfunc()
for example if I do
import random
u.nonfunction()
and then I run it I get
AttributeError: 'module' object has no attribute 'nonfunction'
but if I do a function that it has
import random
random = u.randrange(1,10)
print(random)
It works properly