Reading EXIF gives an error - python-3.x

I'm trying to print the EXIF of an image.
This is my code:
with Image(filename="/home/hapoofesgeli/Desktop/b.jpg") as image:
for k, v in image.metadata.items():
if k.startswith('exif:'):
print(k, v)
But it it gives an error:
Traceback (most recent call last):
File "/home/hapoofesgeli/Programming/Test/Test.py", line 5, in <module>
for k, v in image.metadata.items():
File "/usr/lib/python3.3/collections/abc.py", line 480, in __iter__
yield (key, self._mapping[key])
File "/usr/lib/python3.3/site-packages/wand/image.py", line 2260, in __getitem__
raise TypeError('k must be a string, not ' + repr(format))
TypeError: k must be a string, not <built-in function format>
How to solve this error?

you should use the _getexif() method of that comes bundled in PIL's Image module:
>>> image = Image.open(os.getcwd() + '/canon-ixus.jpg')
>>> image._getexif()
{36864: '0210', 37121: '\x01\x02\x03\x00', .... }
or also image.info['exif']:
>>> image.info['exif'][0:20]
'Exif\x00\x00II*\x00\x08\x00\x00\x00\t\x00\x0f\x01\x02\x00'

Related

What type do I need to pass to multiprocessing.Value for tables object

I have a table object that I want to pass it to multiple threads. I use multiprocessing.Value function to create a semaphore for that object. However, it tells me that Float32Atom is not hashable. Not sure what to do in this case?
>>> import tables as tb
>>> f = tb.open_file('dot.h5', 'w')
>>> filters = tb.Filters(complevel=5, complib='blosc')
>>> n_ = 10000
>>> W_hat = f.create_carray(f.root, 'data', tb.Float32Atom(), shape=(n_, n_), filters=filters)
>>> W_hat = Value(tb.Float32Atom(), W_hat)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lib/python3.8/multiprocessing/context.py", line 135, in Value
return Value(typecode_or_type, *args, lock=lock,
File "/home/lib/python3.8/multiprocessing/sharedctypes.py", line 74, in Value
obj = RawValue(typecode_or_type, *args)
File "/home/lib/python3.8/multiprocessing/sharedctypes.py", line 48, in RawValue
type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
TypeError: unhashable type: 'Float32Atom'
If it is correct that you have only threads (and no processes), you can just use multiprocessing.Semaphore. All threads run in the same context, so you can use it for all of them.
see https://docs.python.org/3/library/threading.html#semaphore-objects

TypeError: 'tuple' object is not callable when converting a list to tuple as return value

I want to convert the final list as tuple. However i am receiving an error.How can i get rid of this?
li= [(19343160,),(39343169,)]
def render_list_sql(li):
l = []
for index, tuple in enumerate(li):
idd = str(tuple[0])
l.append(idd)
return tuple(l)
print(render_list_sql(li))
Expected value to be returned is:
(19343160,39343169)
Error
Traceback (most recent call last):
File "test.py", line 20, in <module>
print(render_list_sql(list))
File "test.py", line 14, in render_list_sql
return tuple(l)
TypeError: 'tuple' object is not callable
As commented, don't use names for variables that mean other things to Python. This is called "shadowing" and you lose the meaning of the original name.
Example:
>>> tuple # This is the class used to create tuples.
<class 'tuple'>
>>> for index,tuple in enumerate([1,2,3]): # This is similar to your code
... print(index,tuple)
...
0 1
1 2
2 3
>>> tuple # tuple is no longer a class, but an instance of an integer.
3
>>> tuple([1,2,3]) # so this fails
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 3([1,2,3]) # You are basically doing this:
<interactive input>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
So don't do that:
li = [(19343160,),(39343169,)] # don't reassign list
def render_list_sql(li):
l = []
for index, tup in enumerate(li): # don't reassign tuple
idd = str(tup[0])
l.append(idd)
return tuple(l) # now this will work
print(render_list_sql(li))
Output:
('19343160', '39343169')
FYI, a shorter version using a generator:
li = [(19343160,),(39343169,)]
tup = tuple(str(i[0]) for i in li)
print(tup)

What does "TypeError: 'NoneType' object is not subscriptable" mean?

I am writing a snake game using Pygame in Python3. However, I keep getting this TypeError, not only do I have no idea what it means I have no idea how to fix it
I haven't really attempted anything as I have no idea what it is or how to fix it. This is the code:
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
The error message I keep getting is:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable
This occurs when you try to index through a Nonetype object, e.g.,
>>> x = None
>>> x[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x[0]
TypeError: 'NoneType' object is not subscriptable
To properly solve your problem, please post the full code or where you set the initial value of self.pos. It seems that you're setting this variable to None.
This appears to be an excerpt from the python tutorial by Tech With Tim: https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/
It is actually caused by a misplaced return inside of the randomSnack while loop.
Full code here: https://pastebin.com/embed_js/jB6k06hG
If the return is inside the while loop (at line 162 in the pastebin) you get this error. I was following the same tutorial and got this error too.
# When you call (line 145)
snack.draw(surface)
# you are referencing the snack that was created with (line 193)
snack = cube(randomSnack(rows, s), color=(0,255,0))
# The randomSnack function returns an x and y (line 162)
return (x,y)
# that gets passed into the cube object's "start" parameter (line 12)
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):

Python Multiprocessing( TypeError: cannot serialize '_io.BufferedReader' object )

I'm trying to make dictionary attack on zip file using Pool to increase speed.
But I face next error in Python 3.6, while it works in Python 2.7:
Traceback (most recent call last):
File "zip_crack.py", line 42, in <module>
main()
File "zip_crack.py", line 28, in main
for result in results:
File "/usr/lib/python3.6/multiprocessing/pool.py", line 761, in next
raise value
File "/usr/lib/python3.6/multiprocessing/pool.py", line 450, in _ handle_tasks
put(task)
File "/usr/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot serialize '_io.BufferedReader' object
I tried to search for same errors but couldn't find answer that can help here.
Code looks like this
def crack(pwd, f):
try:
key = pwd.strip()
f.extractall(pwd=key)
return True
except:
pass
z_file = zipfile.ZipFile("../folder.zip")
with open('words.dic', 'r') as passes:
start = time.time()
lines = passes.readlines()
pool = Pool(50)
results = pool.imap_unordered(partial(crack, f=z_file), lines)
pool.close()
for result in results:
if result:
pool.terminate()
break
pool.join()
I also tried another approach using map
with contextlib.closing(Pool(50)) as pool:
pool.map(partial(crack, f=z_file), lines)
which worked great and found passwords quickly in Python 2.7 but it throws same exception in python 3.6

python: TypeError: expected string or buffer: can't reproduce error with prompt

I am trying to debug this function:
def check_domains(url):
global num_websites,domain_queue,domains,doc_queue,stanford_tagger
the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url)
if the_domain is not None:
if the_domain.groups(0)[1] not in domains.keys():
domains[the_domain.groups(0)[1]] = website(doc_queue,the_domain.groups(0)[1])
domains[the_domain.groups(0)[1]].add_initial_url(url)
domain_queue.append(domains[the_domain.groups(0)[1]])
num_websites = num_websites + 1
else:
domains[the_domain.groups(0)[1]].add_url(url)
error:
File "web_crawler.py", line 178, in getdoc
check_domains(check)
File "web_crawler.py", line 133, in check_domains
the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url)
File "/usr/local/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
I try and be a good boy and test in interactive mode:
>>> def check_domains(url):
... the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url) #right here
... if the_domain is not None:
... print the_domain.groups(0)[1]
... else:
... print "NOOOO!!!!!"
...
>>>
>>> check_domains("http://www.hulu.com/watch/6704")
hulu.com
>>> check_domains("https://docs.python.org/2/library/datetime.html")
python.org
so this does what I want it to do and I didn't change that line. But why???
The value of url can still be None and that's what gives this error:
>>> re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$', None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
So you should check whether the object that you're passing for url is indeed a string. It may even be a number or something else but it's not a string which is what the matching function expects.

Resources