Receiving the below error when running my script:
Traceback (most recent call last):
File "HC_Main.py", line 54, in <module>
setup_exists = os.path.isfile(config_file)
AttributeError: 'function' object has no attribute 'isfile'
Sample code is:
import os
setup_exists = os.path.isfile(setup_exists)
if setup_exists is False:
print "Setup file exists"
When I checked the IDLE console with dir(os.path), isfile is listed. Additionaly, I can use the function without issues in IDLE as well.
Could it be my IDE causing issues here? I've also tried running the script apart from the IDE, but it still receives the error.
Somehow, os.path is no longer the builtin module, but it has been replaced with a function. Check your code to make sure you didn't accidentally monkey-patch it somewhere.
For clues, you could start by putting:
print os.path
right before the line where you actually use os.path.isfile. This should give you the function's name which will hopefully give you a good place to start looking.
Try
import os.path
instead
see this thread for more info: How do I check whether a file exists using Python?
Found the issue. I had an if/else statement earlier in the code, which was being used to gather the OS version the script was running on. Turns out I used OS (caps) for the variable name, which I think caused this. I changed it around, and it's fixed.
Related
I'm using a 2010 Head First Book for Python, chapter 2. I've created a module called nester, which contains the function print_lol, then made another program which should import nester, create a little list, and then call the function print_lol contained in nester. It doesn't work, tho.
import nester
cast = ["Palin", "Cleese", "Idle", "Jones", "Gilliam", "and Chapman."]
nester.print_lol(cast)
This is the program, and this is the output:
> Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
nester.print_lol(cast)
AttributeError: module 'nester' has no attribute 'print_lol'
What's wrong with that? Why this happens? The code is exactly as in the book, same path, environment paths are ok. What's wrong?
Here is the 'nester' code, and it works properly.
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)
Also, the nester it's in C:\nester. It contains setup.py, nester.py, and the installation folders and files: MANIFEST, Lib, dist, build.
Try this on your python console
dir("nester")
It should show all the available functions. You might need to make sure print_lol is in the list. Most likely, it is under some other sub-tribute. So the way you call it should be nester.some_tribute.print_lol()
Since import nester didn't throw in error, that means your script can import nester. Try (explicit function import)
from nester import print_lol
If this fails, make sure print_lol exist in nester, as in there are no spelling mistakes.
I guess I found out the answer, and it was pretty easy, but I didn't notice that until deeper research on the website with two friends here.
The module where the 'nester' class is put it's called 'nester'. So when I tried to import 'nester', I imported the module, not the class. I changed the code from the question one to:
from nester import nester
cast = ["Palin", "Cleese", "Idle", "Jones", "Gilliam", "and Chapman."]
nester.print_lol(cast)
So I import from 'nester' Module the 'nester' Class.
Pro-tip: NEVER use the same name for Module and Class.
Credits:
I'm getting this error 'module' object has no attribute '_strptime' but only when I use several threads. When I only use one it works fine. Im using python 2.7 x64. Here there us the reduced function i'm calling
import datetime
def get_month(time):
return datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S+0000').strftime("%B").lower()
Here is the complete traceback:
AttributeError: 'module' object has no attribute '_strptime'
Exception in thread Thread-22:
Traceback (most recent call last):
File "C:\Python27x64\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27x64\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\file.py", line 81, in main
month=get_month(eventtime)
File "C:\file.py", line 62, in get_month
return datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S+0000').strftime("%B").lower()
AttributeError: 'module' object has no attribute '_strptime'
I can confirm that the issue is related to multithreading, and it happens to me occasionally when I use datetime.datetime.strptime in combination with the ThreadPool module.
I was able to fix this in my script by importing the "missing" module as follows:
import _strptime
The problem is described in a mailing list message "threading bug in strptime".
datetime.strptime has a problem with Python 2's threading module. The workaround suggested there seems to be to invoke strptime = datetime.datetime.strptime before any threads are started.
Just ran into this exact problem. It's a tricky one - took me an hour or so to track it down. I tried launching the shell and entering in the following code:
import datetime
print(datetime.datetime.strptime("2015-4-4", "%Y-%m-%d"))
This worked fine. Then I tried it in a blank file in my workspace. This gave the same error you described. I tried running it from the command line in my workspace. Still gave the error. I then launched the shell from my workspace. This time it gave the error in the shell environment. As it turned out, any directory other than the one I was in worked fine.
The problem was that my project was a python calendar app, and my main file was called "calendar.py". This conflicted with some native import, thus creating the bizarre error.
In your case, I'd bet anything the problem is the name of your file: "file.py". Call it something else, and you should be good to go.
I was running into this issue when testing out a script that had been working on Linux on a Windows machine, and I was able to fix it by simply adding an import statement at the top of the thread.
def multithreadedFunction():
from datetime import datetime
# Rest of the function
Probably worth trying this out before modifying your function to not use the datetime module, since this is a much quicker fix if it works.
Same error in my thread module which uses the datetime.strptime() method.
As filed in https://bugs.python.org/issue7980, that method does not import _strptime.py in a thread safe way.
One of the last comments says that: "this is a Python 2.7-only bug, and it's not a security issue, so the issue may be closed as either "wontfix" (because we won't fix it in Python 2) or "fixed" (because it is already fixed in Python 3), depending on your perspective."
I somehow managed to get a ModuleNotFoundError: No module named '_strptime' error in python 38, 39, and 310 when using datetime.strptime when running the below code within a gitlab ci pipeline. I haven't found anything like this online, so thought best to put it here for anyone who comes across it.
For example, the following works perfectly locally (and I expect should always work):
from datetime import datetime
my_datetime_object = datetime.strptime(date_string, date_format)
But the above code for some reason caused the ModuleNotFoundError: No module named '_strptime' error.
My roundabout way of fixing this was as follows:
import _strptime # due to gitlab ci problem
from datetime import datetime
my_datetime_object = _strptime._strptime_datetime(datetime, date_string, date_format)
which worked fine.
I have a module called imtools.py that contains the following function:
import os
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
When I attempt to call the function get_imlist from the console using import imtools and imtools.get_imlist(path), I receive the following error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\...\PycharmProjects\first\imtools.py", line 5, in get_imlist
NameError: name 'os' is not defined
I'm new at Python and I must be missing something simple here, but cannot figure this out. If I define the function at the console it works fine. The specific history of this module script is as follows: initially it was written without the import os statement, then after seeing the error above the import os statement was added to the script and it was re-saved. The same console session was used to run the script before and after saving.
Based on small hints, I'm going to guess that your code didn't originally have the import os line in it but you corrected this in the source and re-imported the file.
The problem is that Python caches modules. If you import more than once, each time you get back the same module - it isn't re-read. The mistake you had when you did the first import will persist.
To re-import the imtools.py file after editing, you must use reload(imtools).
Same problem is with me I am also trying to follow the book of Programming Computer Vision with Python by Jan Erik Solem" [http://programmingcomputervision.com/]. I tried to explore on internet to see the problem but I did not find any valuable solution but I have solved this problem by my own effort.
First you just need to place the 'imtools.py' into the parent folder of where your Python is installed like C:\Python so place the file into that destination and type the following command:
from PIL import Image
from numpy import *
from imtools import *
Instead of typing the code with imtools.get_imlist() you just to remove the imtools from the code like:
get_imlist()
This may solve your problem as I had found my solution by the same technique I used.
I am getting back into python and I'm having a really basic issue....
My source has the following...
def calrounds(rounds):
print rounds
When I run this through the shell and try to call calrounds(3) I get..
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
calrounds(3)
NameError: name 'calrounds' is not defined
Its been awhile since I've used python, humor me.
Did you import your source first?
It says that the first line of your program is calling calrounds with a parameter 3. Move that below your function definition. The definition needs to be before you call the function. If you are using python 3.0+ you need parenthesis for the print statement.
>>> def calrounds(rounds):
print(rounds)
>>> calrounds(3)
3
The first thing to do is to look at how you're calling the function. Assuming it's in myModule.py, did you import myModule or did you from myModule import calrounds? If you used the first one, you need to call it as myModule.calrounds().
Next thing I would do is to make sure that you're restarting your interpreter. If you have imported a module, importing it again will not reload the source, but use what is already in memory.
The next posibility is that you're importing a file other than the one you think you are. You might be in a different directory or loading something from the standard library. After you import myModule you should print myModule.__file__ and see if it is the file you think you're working on. After 20 years of programming, I still find myself doing this about once a year and it's incredibly frustrating.
Finally, there's the chance that Python is just acting up. Next to your myModule.py there will be a myModule.pyc - this is where Python puts the compiled code so it can load modules faster. Normally it's smart enough to tell if your source has been modified but, occassionally, it fails. Delete your .pyc file and restart the interpreter.
I have a problem with dbus and python. Running python from the command line, telling it import dbus and then systembus = dbus.SystemBus() results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write, I get this error:
Traceback (most recent call last):
File "dbtest.py", line 26, in <module>
a = getDevs()
File "dbtest.py", line 7, in getDevs
bus = dbus.SystemBus()
AttributeError: 'module' object has no attribute 'SystemBus'
Any ideas as to what I'm doing wrong? I don't think I fully understand the error returned. The code I have so far is:
#!/usr/bin/env python
import dbus
def getDevs():
bus = dbus.SystemBus()
if __name__ == "__main__":
a = getDevs()
The obvious problem is that when you are importing dbus, it is not getting all the methods with it.
In both your program and your friend's, do print dbus.__file__. This will show what .pyc it is using. If they are different, you are not importing the correct dbus module.
I'm going to guess that you are actually importing some random file called dbus.py in your local directory. Or, if your script name is "dbus.py", you are just importing itself and luckily python doesn't import recursively. The easiest solution in this case is to rename the offending file to something else.