How to access filemode attribute of zipfile?
>>> info = zin.infolist()[1]
>>> info
<ZipInfo filename='test_dir/' filemode='drwxr-xr-x' external_attr=0x10>
>>> info.filename
'test_dir/'
>>> info.external_attr
1106051088
>>> info.filemode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'ZipInfo' object has no attribute 'filemode'
The file attributes are stored in the upper bits of external_attr (above the lower 16 bits):
oct(1106051088 >> 16)
#'0o40755'
To check specific permissions, use functions from the module stat, e.g.:
stat.S_ISDIR(1106051088 >> 16)
# True, a directory
stat.S_IRUSR & (1106051088>>16)
# 256, user-readable
stat.S_IWGRP&(1106051088>>16)
# 0, not group-writable
Related
I'm trying to understand the difference between these two mock constructs and when is it appropriate to use either. I tested it in the interpreter, e.g.:
>>> mm = mock.MagicMock(spec=list)
>>> ca = mock.create_autospec(list)
>>> mm
<MagicMock spec='list' id='140372375801232'>
>>> mm()
<MagicMock name='mock()' id='140372384057808'>
>>> mm.append()
<MagicMock name='mock.append()' id='140372375724720'>
>>> mm().append()
<MagicMock name='mock().append()' id='140372375753104'>
>>> ca
<MagicMock spec='list' id='140372384059248'>
>>> ca()
<NonCallableMagicMock name='mock()' spec='list' id='140372384057040'>
>>> ca.append()
<MagicMock name='mock.append()' id='140372375719744'>
>>> ca().append()
<MagicMock name='mock().append()' id='140372375796848'>
>>>
But I can't understand why "constructing" the mock created using create_autospec gives me a NonCallableMagicMock and the MagicMock gives me more MagicMock. The documentation isn't helping much.
The main difference between using the spec argument and using create_autospec is recursiveness. In the first case, the object itself is specced, while the called object is not:
>>> mm = mock.MagicMock(spec=list)
>>> mm
<MagicMock spec='list' id='2868486557120'>
>>> mm.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python\Python38\lib\unittest\mock.py", line 635, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'foo'
>>> mm.append
<MagicMock name='mock.append' id='2868486430240'>
>>> mm.append.foo
<MagicMock name='mock.append.foo' id='2868486451408'>
In the second case, the called objects are also specced (lazily):
>>> ca = mock.create_autospec(list)
>>> ca
<MagicMock spec='list' id='2868486254848'>
>>> ca.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python\Python38\lib\unittest\mock.py", line 635, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'foo'
>>> ca.append
<MagicMock name='mock.append' spec='method_descriptor' id='2868486256336'>
>>> ca.append.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python\Python38\lib\unittest\mock.py", line 635, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'foo'
There is one caveat, that is shown in your example code. If you use create_autospec as shown here, it behaves as if the object is a class, not an instance, so you are able to call it (creating an instance):
>>> ca = mock.create_autospec(list)
>>> ca()
<NonCallableMagicMock name='mock()' spec='list' id='2868485877280'>
If you want to behave it like an instance, you have to use instance=True:
>>> ca = mock.create_autospec(list, instance=True)
>>> ca
<NonCallableMagicMock spec='list' id='2868485875024'>
>>> ca()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NonCallableMagicMock' object is not callable
Note that using mock.patch with autospec=True creates a mock that behaves like the one created using mock.create_autospec, as described in the documentation.
Also note that the return value of a call is always a MagicMock, regardless of the return value of the real call. So, even if a function returns None, like list.append, a mock is returned if calling the method from a mock, regardless of the spec.
codes:
>>> from test2.models import Member_info
>>> member = Member_info.objects.all()
>>> member
<QuerySet [<Member_info: John2>, <Member_info: John1>, <Member_info: John3>]>
>>> member = Member_info.objects.all()[0]
>>> member
<Member_info: gun2>
>>> member += Member_info.obejcts.all()[1]
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: type object 'Member_info' has no attribute 'obejcts'
>>> member += Member_info.objects.all()[1]
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'Member_info' and 'Member_info'
>>> member.append(Member_info.objects.all()[1])
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Member_info' object has no attribute 'append'
2.How can i append,,,,?
You can append to list, but you are trying to append to Member_info. Try this one:
member = Member_info.objects.all()[0]
members = [member]
members.append(Member_info.objects.all()[1])
I have a problem with the following function in python (where swap is a function that I have previously created and that works fine):
def swap (cards):
"""
>>> swap('FBFFFBFFBF')
'BFBBBFBBFB'
>>> swap('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFBB'
>>> swap('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'BBFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFB'
"""
invert=""
for i in cards:
if i is "B":
invert+="F"
else:
invert+="B"
return (invert)
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
indices=""
for pos, i in enumerate(cards):
if i =="B":
indices+=str(pos)
first= int(indices[0])
last= int(indices[-1])
prefix= cards [:first]
middle= cards [first:last+1]
suffix= cards [last+1:]
middle2=swap(middle)
return (prefix+middle2+suffix)
def turns (cards):
"""
>>> turns('FBFFFBFFBF')
3
>>> turns('BFFBFBFFFBFBBBFBBBBFF')
6
>>> turns('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
14
"""
turn=0
while cards != 'F'*len(cards):
cards=swap2(cards)
turn+=1
return (turn)
if __name__ == '__main__':
import doctest
doctest.testmod()
when I run this function it works fine but if I use doctest to see if there are mistakes it tells me:
TypeError: 'str' object is not an iterator
I don't know where this error comes from.
Can anyone help me?
complete output of the doctest:
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 25, in __main__.swap2
Failed example:
next('FBFFFBFFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 27, in __main__.swap2
Failed example:
next('BFFBFBFFFBFBBBFBBBBFF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[1]>", line 1, in <module>
next('BFFBFBFFFBFBBBFBBBBFF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 29, in __main__.swap2
Failed example:
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[2]>", line 1, in <module>
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
TypeError: 'str' object is not an iterator
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
# …
The function is called swap2 but within the doctests, you are using next which happens to be a built-in function that does something completely different. That’s why you are seeing that error.
At times like this, it’s really important to actually look at the error messages. It clearly told you what was called:
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
So if you don’t know where that was supposed to come from, then check out the error message. Doctest will tell you what it is executing: swap2[0], swap2[1], etc. tells you the function name the docstring that is being executed is by doctest and which test case it is (0 is the first, 1 the second etc.). It even gives you the line number (within the doctest case) where the error appeared, and of course the line that was causing the error. So use that information to go to the problematic code, and figure out what the problem is.
I am trying to port to Python some old VBA code.
In VBA I add Geo3D.dll as a project reference, then I use this:
Set P1 = New GEO3DLib.Point
P1.Set 1, 2, 3, 0.001
In Python I tried this:
import comtypes
import comtypes.client as cc
cc.GetModule('C:\\Program Files (x86)\\think3\\2009.3\\thinkdesign\\bin\\Geo3d.dll')
import comtypes.gen.GEO3DLib as Geo3d
pt = cc.CreateObject('Geo3d.Point', None, None, Geo3d.Point)
But I get this error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
pt = cc.CreateObject('Geo3d.Point', None, None, Geo3d.Point)
File "C:\Anaconda3\lib\site-packages\comtypes\client\__init__.py", line 238, in CreateObject
obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
File "C:\Anaconda3\lib\site-packages\comtypes\__init__.py", line 1217, in CoCreateInstance
iid = interface._iid_
AttributeError: type object 'Point' has no attribute '_iid_'
Replacing the last line with:
pt = Geo3d.Point
pt.Set(1., 2., 3., 0.001)
I get this error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
pt.Set(1., 2., 3., 0.001)
AttributeError: type object 'Point' has no attribute 'Set'
Any idea?
Enure that the python implementation and the thinkdesign library are compiled for the same platform type: 64 bit or 32 bit.
I tested this as follows:
>>> p=Dispatch('Geo3d.Point')
>>> p
<win32com.gen_py.think3 thinkdesign Type Library.IPoint instance at 0x59554312>
>>> p.Set(0,0,0)
>>> p.X
0.0
or with comtypes:
>>> point=comtypes.CoCreateInstance(comtypes.GUID.from_progid('Geo3d.Point'))
>>> ipoint=point.QueryInterface(Geo3d.IPoint)
>>> ipoint.Set(0,0,0)
0
>>> ipoint.X
0.0
I would like to know, just for fun, if I can create functions using function class constructor, i.e. without language construct def, just like creating class by instantiating type object. I know, function constructor takes 2 args - code object and globals. But I don't know how I should compile the source properly.
>>> def f():
... pass
>>> Function = type(f)
>>> Function
<class 'function'>
>>> code = compile("x + 10", "<string>", "exec")
>>> f = Function(code, globals())
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> f(20)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <module>() takes 0 positional arguments but 1 was given
You need to set many attributes on the code object, such as co_varnames, co_nlocals, etc.
What clearly works is
code = compile("def foo(n):return n+10", "<string>", "exec").co_consts[0]
func = Function(code, globals())
but I guess this would be considered cheating. To really define the code object from scratch, do (for 3.3)
code = types.CodeType(1, 0, 1, 2, 67, b'|\x00\x00d\x01\x00\x17S', (None, 10),
(), ('x',), '<string>', 'f', 1, b'\x00\x01')
func = Function(code, globals())
print(func(10))
This, of course, requires you to do the entire compile() yourself.
Well, this works:
>>> x = 0
>>> def f(): pass
...
>>> func = type(f)
>>> code = compile("global x\nx += 10","<string>","exec")
>>> nf = func(code,globals())
>>> nf()
>>> x
10
Don't know how you'd pass arguments to the function though.