win32api.FormatMessage() error - python

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.

Related

Replit DB is not loading data into variables

i'm using replits database but when i try to load it in it returns an error
any ideas?
cookie = db[name]
cookiepc = db[name + "cookiepc"]
increase = db[name + "increase"]
the error is
Traceback (most recent call last):
File "main.py", line 25, in <module>
cookiepc = db[name + "cookiepc"]
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 479, in get_raw
raise KeyError(key)
KeyError: 'shdfgwbdhfbadwcookiepc'
According to the documentation for replit-py, a KeyError is raised when an attempt is made to read from a key that doesn't exist in the database.
You can use db.get to specify a default value for if the key doesn't exist:
print(db.get("b", "default")) # default
db["b"] = "pie"
print(db.get("b", "default")) # pie

RasterioIOError: Attempt to create new tiff file failed: Permission denied

I am tring to resample Chirps data from 0.25 to 0.0025degrees resolution with the following code, I am still using 1 as an upscale factor to get the code to run:
import rasterio
from rasterio.enums import Resampling
import os
upscale_factor = 1
i = 0
for files in os.listdir(r'D:/CHIRPS RSDATA/CHIRPS(1981-1983)'):
if files [-4:] == '.tif':
i = i + 1
fp = r'D:\CHIRPS RSDATA\CHIRPS(1981-1983)'+'\\'+files
print(fp)
dataset = rasterio.open(fp)
data = dataset.read(out_shape=(dataset.count,
int(dataset.height*upscale_factor),
int(dataset.width*upscale_factor)),
resampling=Resampling.bilinear) #You can change the resamplng technique here
if data.shape[-1] != 0 and data.shape[-2] != 0:
transform=dataset.transform*dataset.transform.scale((dataset.width/data.shape[-1]),(dataset.height/data.shape[-2]))
height = int(dataset.height*upscale_factor)
width = int(dataset.width*upscale_factor)
with rasterio.Env():
profile = dataset.profile
profile.update(transform=transform,driver='GTiff',height=height,width=width)
with rasterio.open('D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Rainfalls',"w",**profile) as output:
output.write(data)
print("Image resampled...")
and I am getting this error:
runfile('D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Resampling_python.py', wdir='D:/CHIRPS RSDATA/CHIRPS(1981-1983)')
D:\CHIRPS RSDATA\CHIRPS(1981-1983)\chirps-v2.0.1981.01.01.tif
Traceback (most recent call last):
File "rasterio\_io.pyx", line 1139, in rasterio._io.DatasetWriterBase.__init__
File "rasterio\_err.pyx", line 215, in rasterio._err.exc_wrap_pointer
CPLE_OpenFailedError: Attempt to create new tiff file 'D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Rainfalls' failed: Permission denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Resampling_python.py", line 42, in <module>
with rasterio.open('D:\CHIRPS RSDATA\CHIRPS(1981-1983)\Rainfalls',"w",**profile) as output:
File "C:\Users\khoda\anaconda3\lib\site-packages\rasterio\env.py", line 435, in wrapper
return f(*args, **kwds)
File "C:\Users\khoda\anaconda3\lib\site-packages\rasterio\__init__.py", line 225, in open
s = writer(path, mode, driver=driver,
File "rasterio\_io.pyx", line 1143, in rasterio._io.DatasetWriterBase.__init__
RasterioIOError: Attempt to create new tiff file 'D:/CHIRPS RSDATA/CHIRPS(1981-1983)/Rainfalls' failed: Permission denied
I tried changing the permissions of the folder with no luck, I also double checked the synaxes as other people have suggested. Please help.

xlwings error: not opening excel workbook getting an error upon call wb.open

xlwings works fine on my computer, but when I try to transfer the same set up to another computer it seems to not open correctly giving me this error
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 432, in __call__
return Book(xl=self.xl(name_or_index))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 152, in __call__
v = self._inner(*args, **kwargs)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2776, in open
impl = self.impl(name)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 434, in __call__
raise KeyError(name_or_index)
KeyError: 'output2019-06-03.11-40timeseries_5-31-2019scrubbed.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Computation.py", line 157, in <module>
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 488, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\main.py", line 2787, in open
impl = self.impl.open(fullname)
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 443, in open
return Book(xl=self.xl.Open(fullname))
File "C:\Users\base7268\AppData\Local\Programs\Python\Python37\lib\site-packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)
Here is some simplified code where none of the data changing is occurring. Using ospath absolute does not help with the error. Both systems run the same 64 bit operating system and 32 bit excel. Yet the error persists on the second machine. There is no real difference I can understand that would give me an error on the 2nd system over the first one. Both machines are PCs
import xlrd
import openpyxl
import xlwings as xw
from xlwings import constants
import os
import tkinter as tk
from tkinter import filedialog
import datetime
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
start = time.time()
wb = openpyxl.load_workbook(file_path)
Returns = wb['Prices']
newWs = wb.create_sheet()
newWs.title = "NominalDailyReturns"
benchWS = wb.create_sheet()
benchWS.title = "ActiveDailyReturns"
thirdWs = wb.create_sheet()
thirdWs.title = "RawAnalysis"
thirdWs.column_dimensions["A"].width = 32
name4 = thirdWs.title
print("halfway")
print(os.path.split(file_path))
print("output" + timeName + os.path.split(file_path)[1])
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book(os.path.abspath("output" + timeName + os.path.split(file_path)[1]))
XnewWs = xwWb.sheets['NominalDailyReturns']
xwWb.save()
xwWb.close()
wb = openpyxl.load_workbook("output" + timeName + os.path.split(file_path)[1])
benchWS = wb['ActiveDailyReturns']
wb.save("output" + timeName + os.path.split(file_path)[1])
xwWb = xw.Book("output" + timeName + os.path.split(file_path)[1])
XthirdWs = xwWb.sheets['RawAnalysis']
xwWb.save()
xwWb.close()
I figured out the problem with my code. When I used openpyxl to edit my excel data, one of the formulas was subtracting a word from a number, raising an error and corrupting the excel file. Then xlwings tried to open a corrupted file, and it failed on me.
So the solution is to not save a corrupted excel file and expect xlwings to open it.

MDB/ACCDB execute macro/function (with parameters) by python script

I want to execute a macro/function code with python script. I have this code example:
from win32com.client import Dispatch
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.DoCmd.RunMacro('MyMacro')
objAccess.Application.CloseCurrentDatabase()
objAccess.Application.Quit()
del objAccess
del objDB
But I get this error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 8, in <module>
objAccess.DoCmd.RunMacro('MyMacro')
File "<COMObject <unknown>>", line 3, in RunMacro
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, u"Microsoft Office Access can't find the object 'MyMacro.'", u'ACMAIN11.CHM', 10183, -2146825803), None)
Then I try another approach, call RUN method:
objAccess = Dispatch("Access.Application")
objAccess.Visible = False
objAccess.OpenCurrentDatabase(strDbName)
objDB = objAccess.CurrentDb()
objAccess.Run('merge', "mystringparameter")
objAccess.Application.Quit()
error:
Traceback (most recent call last):
File "D:\workspace-python\TOOLS\SHPTOOL\test.py", line 58, in <module> objAccess.Run('merge', "mystringparameter")
File "<COMObject Access.Application>", line 14, in Run
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, u"Microsoft Office Access can't find the procedure 'merge.'", None, -1, -2146825771), None)
And my MDB code, the 3 functions:
Sub merge(path As String)
MsgBox "Inside generated macro!!! " & path
End Sub
Sub MyMacro()
MsgBox "Inside generated macro!!!"
End Sub
Function MyFunction()
MsgBox "You MUST select a Destination Folder!"
End Function
Thanks
Just replace
objAccess.DoCmd.RunMacro('MyMacro')
by
objAccess.run('MyMacro')
\o/

"Member not found." error using win32com

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

Categories