Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\range.py", line 351, in get_loc
return self._range.index(new_key)
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "<ipython-input-18-518ef7ebbd84>", line 4, in myClick2
a.plot(p1.total_payoff()[0],p1.total_payoff()[1])
File "<ipython-input-10-57724152e4a6>", line 59, in total_payoff
prices = self.option_payoff()[0]
File "<ipython-input-10-57724152e4a6>", line 47, in option_payoff
temppayoff += callpayoff(i,j.get_strike(),j.find_bidask()[1])*j.get_quantity()
File "<ipython-input-6-59b6ad5c0680>", line 28, in find_bidask
bid = data['bid'][0]
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 853, in __getitem__
return self._get_value(key)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 961, in _get_value
loc = self.index.get_loc(label)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\range.py", line 353, in get_loc
raise KeyError(key) from err
KeyError: 0
This is the error message I am getting when I try to execute a function by clicking a TKinter button. The function is below, basically it takes some data (x, y), and plots it with matplotlib.
def myClick2():
f = Figure(figsize=(4,4), dpi=100)
a = f.add_subplot(111)
a.plot(p1.total_payoff()[0],p1.total_payoff()[1])
a.grid(True, which='both')
a.axhline(y=0, color='k')
a.axvline(x=0, color='k')
canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canvas.get_tk_widget().grid(row = 8, column = 1)
The error is saying that "total_payoff", which calls "option_payoff", which calls "find_bidask" is leading to the error. Specifically, the part which I assign bid = data['bid'][0].
def find_bidask(self):
if str.upper(self.cp) == 'C':
data = self.data['calls']
else:
data = self.data['puts']
data = data[data['contractSymbol']==self.symbol].reset_index(drop=True)
bid = data['bid'][0]
ask = data['ask'][0]
However, when I run this separately outside of TKinter, it produces no error, and ['bid'][0] is available as a value. I don't understand what is wrong with my code - is it something in the tkinter myclick2 function that is wrong?
Related
The following code
If I run the following code in pdb (i.e. with python -m pdb)
if __name__=='__main__':
import pandas as pd
df=pd.DataFrame([[0,1,2],[63,146, 135]])
df.plot.area()
it fails with a TypeError inside a numpy routine that's called by matplotlib:
> python -m pdb test_dtype.py
> /home/jhaiduce/financial/forecasting/test_dtype.py(1)<module>()
-> if __name__=='__main__':
(Pdb) r
QSocketNotifier: Can only be used with threads started with QThread
--Return--
> /home/jhaiduce/financial/forecasting/test_dtype.py(6)<module>()->None
-> df.plot.area()
(Pdb) c
Traceback (most recent call last):
File "/usr/lib64/python3.10/site-packages/numpy/core/getlimits.py", line 384, in __new__
dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib64/python3.10/pdb.py", line 1726, in main
pdb._runscript(mainpyfile)
File "/usr/lib64/python3.10/pdb.py", line 1586, in _runscript
self.run(statement)
File "/usr/lib64/python3.10/bdb.py", line 597, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "/home/jhaiduce/financial/forecasting/test_dtype.py", line 6, in <module>
df.plot.area()
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_core.py", line 1496, in area
return self(kind="area", x=x, y=y, **kwargs)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_core.py", line 972, in __call__
return plot_backend.plot(data, kind=kind, **kwargs)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py", line 71, in plot
plot_obj.generate()
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 294, in generate
self._post_plot_logic_common(ax, self.data)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 473, in _post_plot_logic_common
self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 561, in _apply_axis_properties
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1201, in get_majorticklabels
ticks = self.get_major_ticks()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1371, in get_major_ticks
numticks = len(self.get_majorticklocs())
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1277, in get_majorticklocs
return self.major.locator()
File "/usr/lib64/python3.10/site-packages/matplotlib/ticker.py", line 2113, in __call__
vmin, vmax = self.axis.get_view_interval()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1987, in getter
return getattr(getattr(self.axes, lim_name), attr_name)
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 781, in viewLim
self._unstale_viewLim()
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 2932, in autoscale_view
handle_single_axis(
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "/usr/lib64/python3.10/site-packages/matplotlib/ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "/usr/lib64/python3.10/site-packages/matplotlib/transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "/usr/lib64/python3.10/site-packages/numpy/core/getlimits.py", line 387, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /usr/lib64/python3.10/site-packages/numpy/core/getlimits.py(387)__new__()
-> dtype = numeric.dtype(type(dtype))
(Pdb)
The error occurs only when run in the debugger; the program runs as normal when run outside the debugger.
Any idea what could be the cause of this?
I'm trying to set a value on this dropdown but am having trouble doing so. I've tried using the .select(index) method and that doesn't do anything. I've tried doing .typekeys("{DOWN 2}"), which usually works, but I think because another dropdown is selected before hand or something, it's not working. My usual workaround for this is to do .expand() and then .type_keys("{DOWN 2}"), and then .type_keys("{ENTER}"). I can't do this last workaround, because the control is not being wrapped as a combobox, as it should be.
Is there a way I can change it's wrapper? I tried:
from pywinauto import controls
test = controls.uia_controls.ComboBoxWrapper(formJobStock.child_window(auto_id='cboStockSize'))
test.expand()
but I get:
Traceback (most recent call last):
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 250, in __resolve_control
ctrl = wait_until_passes(
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uia_controls.py", line 143, in expand
if self.is_expanded():
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 561, in is_expanded
state = self.get_expand_state()
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uia_controls.py", line 188, in get_expand_state
return super(ComboBoxWrapper, self).get_expand_state()
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 556, in get_expand_state
return self.iface_expand_collapse.CurrentExpandCollapseState
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 132, in __get__
value = self.fget(obj)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 210, in iface_expand_collapse
return uia_defs.get_elem_interface(elem, "ExpandCollapse")
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\uia_defines.py", line 233, in get_elem_interface
cur_ptrn = element_info.GetCurrentPattern(ptrn_id)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 379, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 222, in __get_ctrl
ctrl = self.backend.generic_wrapper_class(findwindows.find_element(**ctrl_criteria))
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
elements = find_elements(**kwargs)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 305, in find_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findbestmatch.py", line 536, in find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'element' in 'dict_keys(['Edit', 'Edit0', 'Edit1', 'Edit2', 'Open', 'Button', 'OpenButton'])'
where formJobStock is a window specification:
formJobStock = window.child_window(auto_id='frmJobStock')
and I know it's found because I've done formJobStock.wrapper_object() and it comes up correctly.
It looks like I'm not passing in the element parameter correctly to the controls.controls_uia.ComboBoxWrapper class init call...any idea on how to do that correctly?
I am trying to add a base map to my plot through Contextily, but am getting this error when trying to see the plot.
Traceback (most recent call last):
File "rasterio/_crs.pyx", line 322, in rasterio._crs._CRS.from_epsg
File "rasterio/_err.pyx", line 192, in rasterio._err.exc_wrap_int
rasterio._err.CPLE_AppDefinedError: PROJ: proj_create_from_database: /opt/anaconda3/share/proj/proj.db lacks DATABASE.LAYOUT.VERSION.MAJOR / DATABASE.LAYOUT.VERSION.MINOR metadata. It comes from another PROJ installation.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 196, in process
func(*args, **kwargs)
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/widgets.py", line 1051, in _clicked
self.set_active(closest)
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/widgets.py", line 1077, in set_active
func(self.labels[index].get_text())
File "vis.py", line 1109, in draw_basemap
ctx.add_basemap(ax, crs=properties_geo.crs.to_string())
File "/opt/anaconda3/lib/python3.8/site-packages/contextily/plotting.py", line 139, in add_basemap
left, right, bottom, top = _reproj_bb(
File "/opt/anaconda3/lib/python3.8/site-packages/contextily/plotting.py", line 229, in _reproj_bb
n_l, n_b, n_r, n_t = transform_bounds(s_crs, t_crs, left, bottom, right, top)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/warp.py", line 180, in transform_bounds
xs, ys = transform(src_crs, dst_crs, in_xs, in_ys)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/env.py", line 387, in wrapper
return f(*args, **kwds)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/warp.py", line 65, in transform
return _transform(src_crs, dst_crs, xs, ys, zs)
File "rasterio/_base.pyx", line 1398, in rasterio._base._transform
File "rasterio/_base.pyx", line 1444, in rasterio._base._osr_from_crs
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 496, in from_user_input
return cls.from_string(value, morph_from_esri_dialect=morph_from_esri_dialect)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 384, in from_string
return cls.from_epsg(val)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 333, in from_epsg
obj._crs = _CRS.from_epsg(code)
File "rasterio/_crs.pyx", line 324, in rasterio._crs._CRS.from_epsg
rasterio.errors.CRSError: The EPSG code is unknown. PROJ: proj_create_from_database: /opt/anaconda3/share/proj/proj.db lacks DATABASE.LAYOUT.VERSION.MAJOR / DATABASE.LAYOUT.VERSION.MINOR metadata. It comes from another PROJ installation.
Here is what I am doing in my code:
route = pd.read_excel("0002_D1_0_fixed_out_points_15ft.xls")
geometry = [Point(xy) for xy in zip(route.x_dd, route.y_dd)]
gdf = GeoDataFrame(route, geometry=geometry, crs='EPSG:3857')
fig,ax = plt.subplots()
ax.plot(route['x_dd'], route['y_dd'], 'o', markersize=1)
ctx.add_basemap(ax, crs=gdf.crs.to_string())
plt.show()
I'm assuming this is an issue with how my installations are set up and not the code itself. I've tried doing conda activate base which is the environment I'm in but am still getting the same error. I am on macOS as well
I am trying to run a source code from a Keras tutorial for image recognition. I'm getting this error,
Traceback (most recent call last):
File "ty.py", line 52, in <module>
X, Y = hf['imgs'][:], hf['labels'][:]
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "C:\Users\alams\Anaconda3\envs\tensorflow\lib\site-
packages\h5py\_hl\group.py", line 167, in __getitem__
oid = h5o.open(self.id, self._e(name), lapl=self._lapl)
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5o.pyx", line 190, in h5py.h5o.open
KeyError: "Unable to open object (object 'imgs' doesn't exist)"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "ty.py", line 66, in <module>
label = get_class(img_path)
File "ty.py", line 48, in get_class
return int(img_path.split('/')[-2])
ValueError: invalid literal for int() with base 10: 'Final_Training'
This is my source code:
def get_class(img_path):
return int(img_path.split('/')[-2])
try:
with h5py.File('X.h5') as hf:
X, Y = hf['imgs'][:], hf['labels'][:]
except (IOError,OSError, KeyError):
root_dir = 'Data/Final_Training/Images/'
imgs = []
labels = []
all_img_paths = glob.glob(os.path.join(root_dir, '*/*.ppm'))
np.random.shuffle(all_img_paths)
for img_path in all_img_paths:
try:
img = preprocess_img(io.imread(img_path))
label = get_class(img_path)
imgs.append(img)
labels.append(label)
except (IOError, OSError):
print('missed', img_path)
pass
X = np.array(imgs, dtype='float32')
Y = np.eye(NUM_CLASSES, dtype='uint8')[labels]
with h5py.File('X.h5','w') as hf:
hf.create_dataset('imgs', data=X)
hf.create_dataset('labels', data=Y)
I tried to run this code by removing the int Conversion from the return of the first function. But seems like all the values are not write in X.h5
You have defined img=[] inside except block (locally). That's why it doesn't have access outside the block. Define it outside the block.
def get_class(img_path):
return int(img_path.split('/')[-2])
imgs=[]
labels=[]
#Your code
I work very often with large libraries like pandas, or matplotlib.
This means that exceptions often produce long stack traces.
Since the error is extremely rarely with the library, and extremely often with my own code, I don't need to see the library detail in the vast majority of cases.
A couple of common examples:
Pandas
>>> import pandas as pd
>>> df = pd.DataFrame(dict(a=[1,2,3]))
>>> df['b'] # Hint: there _is_ no 'b'
Here I've attempted to access an unknown key. This simple error produces a stacktrace containing 28 lines:
Traceback (most recent call last):
File "an_arbitrary_python\lib\site-packages\pandas\core\indexes\base.py", line 2393, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'b'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "an_arbitrary_python\lib\site-packages\pandas\core\frame.py", line 2062, in __getitem__
return self._getitem_column(key)
File "an_arbitrary_python\lib\site-packages\pandas\core\frame.py", line 2069, in _getitem_column
return self._get_item_cache(key)
File "an_arbitrary_python\lib\site-packages\pandas\core\generic.py", line 1534, in _get_item_cache
values = self._data.get(item)
File "an_arbitrary_python\lib\site-packages\pandas\core\internals.py", line 3590, in get
loc = self.items.get_loc(item)
File "an_arbitrary_python\lib\site-packages\pandas\core\indexes\base.py", line 2395, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'b'
Knowing that I ended up in hashtable_class_helper.pxi is almost never helpful for me. I need to know where in my code I've messed up.
Matplotlib
>>> import matplotlib.pyplot as plt
>>> import matplotlib.cm as cm
>>> def foo():
... plt.plot([1,2,3], cbap=cm.Blues) # cbap is a typo for cmap
...
>>> def bar():
... foo()
...
>>> bar()
This time, there's a typo in my keyword argument. But I still have to see 25 lines of stack trace:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bar
File "<stdin>", line 2, in foo
File "an_arbitrary_python\lib\site-packages\matplotlib\pyplot.py", line 3317, in plot
ret = ax.plot(*args, **kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\__init__.py", line 1897, in inner
return func(ax, *args, **kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_axes.py", line 1406, in plot
for line in self._get_lines(*args, **kwargs):
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 407, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 395, in _plot_args
seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 302, in _makeline
seg = mlines.Line2D(x, y, **kw)
File "an_arbitrary_python\lib\site-packages\matplotlib\lines.py", line 431, in __init__
self.update(kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 885, in update
for k, v in props.items()]
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 885, in <listcomp>
for k, v in props.items()]
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 878, in _update_property
raise AttributeError('Unknown property %s' % k)
AttributeError: Unknown property cbap
Here I get to find out that I ended on a line in artist.py that raises an AttributeError, and then see directly underneath that the AttributeError was indeed raised. This is not much value add in information terms.
In these trivial, interactive examples, you might just say "Look at the top of the stack trace, not the bottom", but often my foolish typo has occurred within a function so the line I'm interested in is somewhere in the middle of these library-cluttered stack traces.
Is there any way I can make these stack traces less verbose, and help me find the source of the problem, which almost always lies with my own code and not in the libraries I happen to be employing?
You can use traceback to have better control over exception printing. For example:
import pandas as pd
import traceback
try:
df = pd.DataFrame(dict(a=[1,2,3]))
df['b']
except Exception, e:
traceback.print_exc(limit=1)
exit(1)
This triggers the standard exception printing mechanism, but only shows you the first frame of the stack trace (which is the one you care about in your example). For me this produces:
Traceback (most recent call last):
File "t.py", line 6, in <module>
df['b']
KeyError: 'b'
Obviously you lose the context, which will be important when debugging your own code. If we want to get fancy, we can try and devise a test and see how far the traceback should go. For example:
def find_depth(tb, continue_test):
depth = 0
while tb is not None:
filename = tb.tb_frame.f_code.co_filename
# Run the test we're given against the filename
if not continue_test(filename):
return depth
tb = tb.tb_next
depth += 1
I don't know how you're organising and running your code, but perhaps you can then do something like:
import pandas as pd
import traceback
import sys
def find_depth():
# ... code from above here ...
try:
df = pd.DataFrame(dict(a=[1, 2, 3]))
df['b']
except Exception, e:
traceback.print_exc(limit=get_depth(
sys.exc_info()[2],
# The test for which frames we should include
lambda filename: filename.startswith('my_module')
))
exit(1)