I'm having issues accessing a COM object using the Python win32com module, which I don't have when using VBA. See usage/error below. The other parts of the object are functioning OK, but I can't get any of the parameters out of the ResultSet object.
>>> import win32com.client
>>> Aquator = win32com.client.gencache.EnsureDispatch("Aquator.Application")
>>> db = Aquator.LoadDatabase(r"D:\Shared", "AquatorExcel.mdb")
>>> project = Aquator.LoadProject(db, "A simple model", False, False)
>>>
>>> project.ModelRunStart()
<win32com.gen_py.Aquator Water Resource Simulation._ModelRun instance at 0x15264
824>
>>> Aquator.ActiveProject.ModelRuns.Count
1
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet
<win32com.gen_py.Aquator Water Resource Simulation._IResultSet instance at 0x149
19000>
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.Cost
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 463, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 456, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
The equivalent code in the VBA editor within the application functions correctly, returning a float:
Public Sub Test()
MsgBox Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.Cost
End Sub
As far as I can tell, the EnsureDispatch command has done it's job correctly, and recognises the property (along with others, also inaccessible):
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet._prop_map_get_.keys()
['WaterBalanceMl', 'RunDate', 'Parameters', 'DoublePrecision', 'WarningCount', '
FinishDate', 'AmountLost', 'SinglePrecision', 'Status', 'StartDate', 'Descriptio
n', 'AmountLeaked', 'FailureCount', 'AmountAdded', 'ErrorCount', 'AmountStored',
'Name', 'WaterBalancePercent', 'InfoValueList', 'Results', 'States', 'Cost', 'A
mountRemoved', 'Sequences', 'Duration', 'InfoNameList', 'RunTime']
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.meh
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 462, in __getattr__
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr
))
AttributeError: '<win32com.gen_py.Aquator Water Resource Simulation._IResultSet
instance at 0x15175888>' object has no attribute 'meh'
I have tried using .GetCost() (a la Setting a property using win32com), to no avail ("object has no attribute...").
What am I doing wrong here?
It seems the problem is with the win32com module. The equivilent code using the comtypes module functions correctly:
>>> from comtypes.client import CreateObject
>>> Aquator = CreateObject("Aquator.Application")
>>> Database = Aquator.LoadDatabase(r"D:\Shared", "AquatorExcel.mdb")
>>> Project = Aquator.LoadProject(Database, "A simple project", False, False)
>>> ModelRun = Project.ModelRunStart()
>>> print ModelRun.ResultSet.Cost
133432.20
Related
I am trying to get a named Range in code like this:
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
This generates exception:
File "C:/Users/acme/python/s.py", line 149, in <module>
Range(rng_name, index=False).value = df_grouped_a.ix[loc][col]
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\main.py", line 620, in __init__
self.row1 = xlplatform.get_first_row(self.xl_sheet, range_address)
File "C:\Program Files (x86)\Python271\lib\site-packages\xlwings\_xlwindows.py", line 122, in get_first_row
return xl_sheet.Range(range_address).Row
File "<COMObject <unknown>>", line 3, in Range
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
It might be related to the named range issue, but I would like to get the meaning of error code -2146827284 first.
Unfortunately, the way described here does not work for me: https://stackoverflow.com/a/36080159
Namely:
>>> import win32api
>>> win32api.FormatMessage(-2146827284)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pywintypes.error: (15100, 'FormatMessage', 'The resource loader failed to find MUI file.')
How can I find the error message corresponding to this error code?
-2146827284 may be represented as 0x80020009, is a COM Error Code. That mean DISP_E_EXCEPTION - Basic value returned if COM exception ooccured.
Simpliest way to 'convert' singed int to unsigned is to apply bitwise & 0xFFFFFFFF operation.
>>> error = -2146827284
>>> error & 0xffffffff
2147614729
But nothing special you will see when try to
>>> win32api.FormatMessage(error)
Exception occurred.
I have a Mongo Document with some fields (_id, id, name, status, etc...). I wrote a typical document in a class(like a model would do):
class mod(Document):
id=fields.IntField()
name = fields.StringField()
status=fields.StringField()
description_summary = fields.StringField()
_id = fields.ObjectIdField()
And with this model, I tried to access them:
>>> from mongoengine import *
>>> from api.models import *
>>> connect('doc')
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
I tried to fetch all the entries in the "mod" document: It Worked! I can get all the fields of all the entries (id, name, etc...)
>>> mod_ = mod.objects.all()
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
I tried to filter and return all the entries with the field "status" = "Incomplete": It works, just like before.I tried to filter other fields: it works too
>>> mod_ = mod.objects(status="Incomplete")
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
But When I try to filter with the id I don't manage to get a result:
>>> mod_ = mod.objects(id=102)
>>> mod_[0].name
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
>>> mod_[0].id
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
So I tried with mod.objects.get(id=102)
>>> mod_ = mod.objects.get(id=102)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 271, in get
raise queryset._document.DoesNotExist(msg)
api.models.DoesNotExist: mod matching query does not exist.
Mod matching query does not exist, so it doesn't recognize the id field but when I write mod_[0].id I do have a result, so what can be wrong?
EDIT: I believe that when writing mod.objects(id=102), the field id is interpreted as the _id. How can I specify, I want to query by id and not _id? My Document is already written, so I cannot change the name of the fields.
So, the problem does not come from the difference between _id and id, like said #HourGlass. The values of the id field were stored as integer, I wrote fields.IntField() for the id field, and called mod.objects(id=102) (without quotes).
But for some reason, I have to write them as fields.StringField(), and call mod.objects(id='102').
I'm trying to use qmath, a quaternion lib.
this
from qmath import qmathcore
a = qmathcore.quaternion([1,2,3,4])
print a.conj()
gives me such traceback
Traceback (most recent call last):
File "*******/q_test.py", line 25, in <module>
print str(a.conj())
File "*******/venv/lib/python2.7/site-packages/qmath/qmathcore.py", line 788, in conj
return self.real() - self.imag()
File "*******/venv/lib/python2.7/site-packages/qmath/qmathcore.py", line 762, in imag
return self - self.real()
File "*******/venv/lib/python2.7/site-packages/qmath/qmathcore.py", line 522, in __sub__
self -= other
File "*******/venv/lib/python2.7/site-packages/qmath/qmathcore.py", line 407, in __isub__
self.other = quaternion(other)
File "*******/venv/lib/python2.7/site-packages/qmath/qmathcore.py", line 81, in __init__
self.q = q.q
AttributeError: quaternion instance has no attribute 'q'
but in docs they said, that this must work:
def conj(self):
"""
Returns the conjugate of the quaternion
>>> import qmathcore
>>> a = qmathcore.quaternion([1,2,3,4])
>>> a.conj()
(1.0-2.0i-3.0j-4.0k)
>>> a = qmathcore.hurwitz([1,2,3,4])
>>> a.conj()
(1-2i-3j-4k)
"""
return self.real() - self.imag()
what is this?
qmathcore.py fails its own doctest with a newer (1.9) numpy.
Adding this test to quatereon()
elif isinstance(q,float) or isinstance(q,int): # accept np.float64
self.q = 1.0 * np.array([q,0.,0.,0.])
allows qmath.quaternion([1,2,3,4]).imag() (and conj).
The quaternion method is using a lot of type(q)==xxx tests. isinstance() is a more robust test. Also it ends with a else:pass, and thus doesn't catch q values that it can't handle.
After correcting some import errors, the qmathcore doctest runs fine.
I got an error while run python proxy.py
$ python proxy.py
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most recent call last):
File "proxy.py", line 2210, in <module>
main()
File "proxy.py", line 2180, in main
pre_start()
File "proxy.py", line 2157, in pre_start
common.set_appids(get_appids())
File "proxy.py", line 94, in get_appids
fly = bytes.maketrans(
AttributeError: type object 'str' has no attribute 'maketrans'
The proxy.py file in https://code.google.com/p/smartladder/,
def get_appids():
fly = bytes.maketrans(
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = str(d, encoding='ascii').split('\r\n')
random.shuffle(e)
return e
You are running code written for Python 3, with Python 2. This won't work.
maketrans is a classmethod on the bytes built-in type, but only in Python 3.
# Python 3
>>> bytes
<class 'bytes'>
>>> bytes.maketrans
<built-in method maketrans of type object at 0x10aa6fe70>
In Python 2, bytes is an alias for str, but that type does not have that method:
# Python 2.7
>>> bytes
<type 'str'>
>>> bytes.maketrans
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
Run your code with Python 3 instead, or translate all code in this project to Python 2; the latter requires in-depth knowledge of how Python 2 and 3 differ and is likely a major undertaking.
Just the illustrated function, translated to Python 2, would be:
import string
import urllib2
import base64
import random
def get_appids():
fly = string.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = unicode(d, encoding='ascii').split(u'\r\n')
random.shuffle(e)
return e
Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1354, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes
>>>
I don´t know how to solve this error because I don´t understand it.
Thank you so much.
You have to open your filehandler in binary mode, use wb instead of w:
filehandler = open(b"fruits.obj","wb")