opening computer files using kivy, getting a unicode error - python

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.config import Config
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
Config.set('graphics', 'fullscreen', '0')#keeps screen in a smaller window when running
Config.write()
import os
class MyWidget(BoxLayout):
def __init__(self, **kwargs):
super(MyWidget,self).__init__(**kwargs)
container = BoxLayout(orientation='vertical')
filechooser = FileChooserListView()
filechooser.bind(on_selection=lambda x: self.selected(filechooser.selection))
open_btn = Button(text='open', size_hint=(1, .2))
open_btn.bind(on_release=lambda x: self.open(filechooser.path, filechooser.selection))
container.add_widget(filechooser)
container.add_widget(open_btn)
self.add_widget(container)
def open(self, path, filename):
print(filename)
if len(filename) > 0:
with open(os.path.join(path, filename[0])) as f:
print(f.read())
def selected(self, filename):
print("selected: %s" % filename[0])
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
I am trying to create a program that can open files in kivy, I have a feeling its something to do with my 'os.path.join' I tried to add 'enconding =utf-8' to the area in the code where it says 'with open' that did not work in both cases. Below is the full error, maybe im missing something but hopefully the full error will help.
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-1-ad2b3c0779e3> in <module>
45
46 if __name__ == '__main__':
---> 47 MyApp().run()
~\anaconda3\lib\site-packages\kivy\app.py in run(self)
853
854 self.dispatch('on_start')
--> 855 runTouchApp()
856 self.stop()
857
~\anaconda3\lib\site-packages\kivy\base.py in runTouchApp(widget, slave)
502 _run_mainloop()
503 else:
--> 504 EventLoop.window.mainloop()
505 finally:
506 stopTouchApp()
~\anaconda3\lib\site-packages\kivy\core\window\window_sdl2.py in mainloop(self)
745 while not EventLoop.quit and EventLoop.status == 'started':
746 try:
--> 747 self._mainloop()
748 except BaseException as inst:
749 # use exception manager first
~\anaconda3\lib\site-packages\kivy\core\window\window_sdl2.py in _mainloop(self)
477
478 def _mainloop(self):
--> 479 EventLoop.idle()
480
481 # for android/iOS, we don't want to have any event nor executing our
~\anaconda3\lib\site-packages\kivy\base.py in idle(self)
340
341 # read and dispatch input from providers
--> 342 self.dispatch_input()
343
344 # flush all the canvas operation
~\anaconda3\lib\site-packages\kivy\base.py in dispatch_input(self)
325 post_dispatch_input = self.post_dispatch_input
326 while input_events:
--> 327 post_dispatch_input(*pop(0))
328
329 def idle(self):
~\anaconda3\lib\site-packages\kivy\base.py in post_dispatch_input(self, etype, me)
291 wid.dispatch('on_touch_up', me)
292 else:
--> 293 wid.dispatch('on_touch_up', me)
294
295 wid._context.pop()
kivy\_event.pyx in kivy._event.EventDispatcher.dispatch()
~\anaconda3\lib\site-packages\kivy\uix\behaviors\button.py in on_touch_up(self, touch)
177 else:
178 self._do_release()
--> 179 self.dispatch('on_release')
180 return True
181
kivy\_event.pyx in kivy._event.EventDispatcher.dispatch()
kivy\_event.pyx in kivy._event.EventObservers.dispatch()
kivy\_event.pyx in kivy._event.EventObservers._dispatch()
<ipython-input-1-ad2b3c0779e3> in <lambda>(x)
23
24 open_btn = Button(text='open', size_hint=(1, .2))
---> 25 open_btn.bind(on_release=lambda x: self.open(filechooser.path, filechooser.selection))
26
27 container.add_widget(filechooser)
<ipython-input-1-ad2b3c0779e3> in open(self, path, filename)
33 if len(filename) > 0:
34 with open(os.path.join(path, filename[0])) as f:
---> 35 print(f.read())
36
37 def selected(self, filename):
~\anaconda3\lib\encodings\cp1252.py in decode(self, input, final)
21 class IncrementalDecoder(codecs.IncrementalDecoder):
22 def decode(self, input, final=False):
---> 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0]
24
25 class StreamWriter(Codec,codecs.StreamWriter):
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 57: character maps to <undefined>
​

Related

AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

I am trying to open an image with skimage.io.imread but I have the error in title.
For example:
skimage.io.imread('myimage.png')
My environment; skimage:
import skimage
print(skimage.__version__)
0.19.2
and PIL:
import PIL
PIL.__version__
8.0.1
This is the entire traceback:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-52-1b9f5663f4c8> in <module>
----> 1 skimage.io.imread('qrcode-caracciolo.png')
/usr/local/lib/python3.9/site-packages/skimage/io/_io.py in imread(fname, as_gray, plugin, **plugin_args)
51
52 with file_or_url_context(fname) as fname:
---> 53 img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
54
55 if not hasattr(img, 'ndim'):
/usr/local/lib/python3.9/site-packages/skimage/io/manage_plugins.py in call_plugin(kind, *args, **kwargs)
205 (plugin, kind))
206
--> 207 return func(*args, **kwargs)
208
209
/usr/local/lib/python3.9/site-packages/skimage/io/_plugins/imageio_plugin.py in imread(*args, **kwargs)
8 #wraps(imageio_imread)
9 def imread(*args, **kwargs):
---> 10 return np.asarray(imageio_imread(*args, **kwargs))
/usr/local/lib/python3.9/site-packages/imageio/__init__.py in imread(uri, format, **kwargs)
94 )
95
---> 96 return imread_v2(uri, format=format, **kwargs)
97
98
/usr/local/lib/python3.9/site-packages/imageio/v2.py in imread(uri, format, **kwargs)
199 imopen_args["legacy_mode"] = True
200
--> 201 with imopen(uri, "ri", **imopen_args) as file:
202 return file.read(index=0, **kwargs)
203
/usr/local/lib/python3.9/site-packages/imageio/core/imopen.py in imopen(uri, io_mode, plugin, format_hint, legacy_mode, **kwargs)
212
213 try:
--> 214 plugin_instance = candidate_plugin(request, **kwargs)
215 except InitializationError:
216 # file extension doesn't match file type
/usr/local/lib/python3.9/site-packages/imageio/config/plugins.py in partial_legacy_plugin(request)
106
107 def partial_legacy_plugin(request):
--> 108 return LegacyPlugin(request, legacy_plugin)
109
110 clazz = partial_legacy_plugin
/usr/local/lib/python3.9/site-packages/imageio/core/legacy_plugin_wrapper.py in __init__(self, request, legacy_plugin)
66 )
67 if self._request.mode.io_mode == IOMode.read:
---> 68 if not self._format.can_read(request):
69 raise InitializationError(
70 f"`{self._format.name}`" f" can not read `{source}`."
/usr/local/lib/python3.9/site-packages/imageio/core/format.py in can_read(self, request)
242 Get whether this format can read data from the specified uri.
243 """
--> 244 return self._can_read(request)
245
246 def can_write(self, request):
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _can_read(self, request)
262
263 def _can_read(self, request):
--> 264 Image = self._init_pillow()
265 if request.mode[1] in (self.modes + "?"):
266 if self.plugin_id in Image.OPEN:
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _init_pillow(self)
256
257 if self.plugin_id in ("PNG", "JPEG", "BMP", "GIF", "PPM"):
--> 258 Image.preinit()
259 else:
260 Image.init()
/usr/local/lib/python3.9/site-packages/PIL/Image.py in preinit()
365 assert JpegImagePlugin
366 except ImportError:
--> 367 pass
368 try:
369 from . import PpmImagePlugin
/usr/local/lib/python3.9/site-packages/PIL/JpegImagePlugin.py in <module>
42 import warnings
43
---> 44 from . import Image, ImageFile, TiffImagePlugin
45 from ._binary import i16be as i16
46 from ._binary import i32be as i32
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in <module>
425
426
--> 427 class ImageFileDirectory_v2(MutableMapping):
428 """This class represents a TIFF tag directory. To speed things up, we
429 don't decode tags unless they're asked for.
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in ImageFileDirectory_v2()
706 (TiffTags.DOUBLE, "d", "double"),
707 (TiffTags.IFD, "L", "long"),
--> 708 (TiffTags.LONG8, "Q", "long8"),
709 ],
710 )
AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

NotImplementedError: Failed in nopython mode pipeline. Use of unknown opcode MAP_ADD at line 116 of <ipython-input-287-147d4798a88b>

I try to launch a code with Numba and I get errors.
What I want to do is to compute the cosine similarity with a cosinus_sparse function. This class method I use in the search class method, then I call search in the results method. Although I added the #jit decorator before each method I have this implementation error that appears.
Here is my code:
import numpy as np
from numba import jit
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
import pandas as pd
import math
class Search:
def __init__(self, corpus, method='XTERM', stop_words='english', max_df=1.0, min_df=1, max_features=None):
self.corpus = corpus
self.method = method
self.stop_words = stop_words
self.max_df = max_df
self.min_df = min_df
self.max_features = max_features
self.vectorization()
self.get_shape()
self.features_names = self.bag_of_word.get_feature_names()
def vectorization(self):
if self.method == 'XTERM':
self.bag_of_word = CountVectorizer(stop_words=self.stop_words,
max_df=self.max_df, min_df=self.min_df,
max_features=self.max_features)
self.corpus_vectorized = self.bag_of_word.fit_transform(self.corpus)
elif self.method == 'TFxIDF':
self.bag_of_word = TfidfVectorizer(stop_words=self.stop_words,
max_df=self.max_df, min_df=self.min_df,
max_features=self.max_features)
self.corpus_vectorized = self.bag_of_word.fit_transform(self.corpus)
else:
raise MethodError('Method provided is not valid')
def get_shape(self):
self.n_docs, self.n_terms = self.corpus_vectorized.shape
def get_query(self, query):
self.indexes = [self.features_names.index(q) for q in query if q in self.features_names]
self.query_vec = np.zeros(self.n_terms)
self.query_vec[self.indexes] = 1
#staticmethod
#jit(nopython=True)
def cosinus_sparse(i, j):
num = i.dot(j)
spars = i * i.transpose()
den = math.sqrt(spars[0, 0]) * math.sqrt(sum(j * j))
if (den > 0):
return int(num) / den
else:
return 0
#jit(nopython=True)
def search(self, q) -> dict:
cc = {i: self.cosinus_sparse(self.corpus_vectorized[i, :], q) for i in range(self.n_docs)}
cc = sorted(cc.items(), key=lambda x: x[1], reverse=True)
return cc
#jit
def get_result(self) -> list:
self.result = self.search(self.query_vec)
def result_announcer(self):
self.search_lenght = len([i for i in self.result if i[1] > 0])
print('{} documents linked to your query where found'.format(search_lenght))
def verif_query_vec(self, query):
if int(sum(self.query_vec)) != len(query):
raise QueryError('Error in query or query_vec')
def processing(self, query):
try:
self.get_query(query)
self.verif_query_vec(query)
self.get_result()
except NameError:
self.vectorisation()
self.get_shape()
self.get_feature_names()
self.get_query(query)
self.verif_query_vec(query)
self.get_result()
import ipywidgets as widgets
from IPython.display import display
text = widgets.Text(
value='',
placeholder='Type words',
description='String:',
disabled=False
)
method_radio = widgets.RadioButtons(
options=['XTERM', 'TFxIDF'],
# value='TF',
description='Method:',
disabled=False
)
submit = widgets.Button(description = 'Search')
display(widgets.VBox([text, radio, submit]))
def handle_submit(sender):
global query
query = text.value.lower().split(' ')
method = method_radio.value
# instentiation de l'objet de recherche
global search_obj
search_obj = Search(corpus=corpus, method=method, )
search_obj.processing(query)
submit.on_click(handle_submit)
Here is the error
NotImplementedError Traceback (most recent call last)
<ipython-input-288-025a488daa60> in handle_submit(sender)
27 global search_obj
28 search_obj = Search(corpus=corpus, method=method, )
---> 29 search_obj.processing(query)
30
31 submit.on_click(handle_submit)
<ipython-input-287-147d4798a88b> in processing(self, query)
167 self.get_query(query)
168 self.verif_query_vec(query)
--> 169 self.get_result()
170
171 except NameError:
~\Anaconda3\lib\site-packages\numba\dispatcher.py in _compile_for_args(self, *args, **kws)
365 e.patch_message(''.join(e.args) + help_msg)
366 # ignore the FULL_TRACEBACKS config, this needs reporting!
--> 367 raise e
368
369 def inspect_llvm(self, signature=None):
~\Anaconda3\lib\site-packages\numba\dispatcher.py in _compile_for_args(self, *args, **kws)
322 argtypes.append(self.typeof_pyval(a))
323 try:
--> 324 return self.compile(tuple(argtypes))
325 except errors.TypingError as e:
326 # Intercept typing error that may be due to an argument
~\Anaconda3\lib\site-packages\numba\compiler_lock.py in _acquire_compile_lock(*args, **kwargs)
30 def _acquire_compile_lock(*args, **kwargs):
31 with self:
---> 32 return func(*args, **kwargs)
33 return _acquire_compile_lock
34
~\Anaconda3\lib\site-packages\numba\dispatcher.py in compile(self, sig)
653
654 self._cache_misses[sig] += 1
--> 655 cres = self._compiler.compile(args, return_type)
656 self.add_overload(cres)
657 self._cache.save_overload(sig, cres)
~\Anaconda3\lib\site-packages\numba\dispatcher.py in compile(self, args, return_type)
80 args=args, return_type=return_type,
81 flags=flags, locals=self.locals,
---> 82 pipeline_class=self.pipeline_class)
83 # Check typing error if object mode is used
84 if cres.typing_error is not None and not flags.enable_pyobject:
~\Anaconda3\lib\site-packages\numba\compiler.py in compile_extra(typingctx, targetctx, func, args, return_type, flags, locals, library, pipeline_class)
924 pipeline = pipeline_class(typingctx, targetctx, library,
925 args, return_type, flags, locals)
--> 926 return pipeline.compile_extra(func)
927
928
~\Anaconda3\lib\site-packages\numba\compiler.py in compile_extra(self, func)
372 self.lifted = ()
373 self.lifted_from = None
--> 374 return self._compile_bytecode()
375
376 def compile_ir(self, func_ir, lifted=(), lifted_from=None):
~\Anaconda3\lib\site-packages\numba\compiler.py in _compile_bytecode(self)
855 """
856 assert self.func_ir is None
--> 857 return self._compile_core()
858
859 def _compile_ir(self):
~\Anaconda3\lib\site-packages\numba\compiler.py in _compile_core(self)
842 self.define_pipelines(pm)
843 pm.finalize()
--> 844 res = pm.run(self.status)
845 if res is not None:
846 # Early pipeline completion
~\Anaconda3\lib\site-packages\numba\compiler_lock.py in _acquire_compile_lock(*args, **kwargs)
30 def _acquire_compile_lock(*args, **kwargs):
31 with self:
---> 32 return func(*args, **kwargs)
33 return _acquire_compile_lock
34
~\Anaconda3\lib\site-packages\numba\compiler.py in run(self, status)
253 # No more fallback pipelines?
254 if is_final_pipeline:
--> 255 raise patched_exception
256 # Go to next fallback pipeline
257 else:
~\Anaconda3\lib\site-packages\numba\compiler.py in run(self, status)
244 try:
245 event(stage_name)
--> 246 stage()
247 except _EarlyPipelineCompletion as e:
248 return e.result
~\Anaconda3\lib\site-packages\numba\compiler.py in stage_inline_pass(self)
582 self.flags.auto_parallel,
583 self.parfor_diagnostics.replaced_fns)
--> 584 inline_pass.run()
585 # Remove all Dels, and re-run postproc
586 post_proc = postproc.PostProcessor(self.func_ir)
~\Anaconda3\lib\site-packages\numba\inline_closurecall.py in run(self)
75
76 if guard(self._inline_closure,
---> 77 work_list, block, i, func_def):
78 modified = True
79 break # because block structure changed
~\Anaconda3\lib\site-packages\numba\ir_utils.py in guard(func, *args, **kwargs)
1358 """
1359 try:
-> 1360 return func(*args, **kwargs)
1361 except GuardException:
1362 return None
~\Anaconda3\lib\site-packages\numba\inline_closurecall.py in _inline_closure(self, work_list, block, i, func_def)
212 inline_closure_call(self.func_ir,
213 self.func_ir.func_id.func.__globals__,
--> 214 block, i, func_def, work_list=work_list)
215 return True
216
~\Anaconda3\lib\site-packages\numba\inline_closurecall.py in inline_closure_call(func_ir, glbls, block, i, callee, typingctx, arg_typs, typemap, calltypes, work_list)
253 callee_closure = callee.closure if hasattr(callee, 'closure') else callee.__closure__
254 # first, get the IR of the callee
--> 255 callee_ir = get_ir_of_code(glbls, callee_code)
256 callee_blocks = callee_ir.blocks
257
~\Anaconda3\lib\site-packages\numba\ir_utils.py in get_ir_of_code(glbls, fcode)
1572 f.__name__ = fcode.co_name
1573 from numba import compiler
-> 1574 ir = compiler.run_frontend(f)
1575 # we need to run the before inference rewrite pass to normalize the IR
1576 # XXX: check rewrite pass flag?
~\Anaconda3\lib\site-packages\numba\compiler.py in run_frontend(func)
168 interp = interpreter.Interpreter(func_id)
169 bc = bytecode.ByteCode(func_id=func_id)
--> 170 func_ir = interp.interpret(bc)
171 post_proc = postproc.PostProcessor(func_ir)
172 post_proc.run()
~\Anaconda3\lib\site-packages\numba\interpreter.py in interpret(self, bytecode)
101 # Data flow analysis
102 self.dfa = dataflow.DataFlowAnalysis(self.cfa)
--> 103 self.dfa.run()
104
105 # Temp states during interpretation
~\Anaconda3\lib\site-packages\numba\dataflow.py in run(self)
26 def run(self):
27 for blk in self.cfa.iterliveblocks():
---> 28 self.infos[blk.offset] = self.run_on_block(blk)
29
30 def run_on_block(self, blk):
~\Anaconda3\lib\site-packages\numba\dataflow.py in run_on_block(self, blk)
76 for offset in blk:
77 inst = self.bytecode[offset]
---> 78 self.dispatch(info, inst)
79 return info
80
~\Anaconda3\lib\site-packages\numba\dataflow.py in dispatch(self, info, inst)
86 fname = "op_%s" % inst.opname.replace('+', '_')
87 fn = getattr(self, fname, self.handle_unknown_opcode)
---> 88 fn(info, inst)
89
90 def handle_unknown_opcode(self, info, inst):
~\Anaconda3\lib\site-packages\numba\dataflow.py in handle_unknown_opcode(self, info, inst)
91 msg = "Use of unknown opcode {} at line {} of {}"
92 raise NotImplementedError(msg.format(inst.opname, inst.lineno,
---> 93 self.bytecode.func_id.filename))
94
95 def dup_topx(self, info, inst, count):
NotImplementedError: Failed in nopython mode pipeline (step: inline calls to locally defined closures)
Use of unknown opcode MAP_ADD at line 116 of <ipython-input-287-147d4798a88b>
How do I fix this error?
Thanks a lot for your help.

why kivy gives error in starting of the code?

I downloaded kivy successfully.
When I was trying to start the kivy window with this command that I found at the original kivy basics web site:
import kivy
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text='Hello world')
if __name__ == '__main__':
MyApp().run()
It gives an error:
ArgumentError Traceback (most recent call last)
D:\Anaconda\lib\site-packages\kivy\core\window\window_sdl2.py in mainloop(self)
746 try:
--> 747 self._mainloop()
748 except BaseException as inst:
D:\Anaconda\lib\site-packages\kivy\core\window\window_sdl2.py in _mainloop(self)
478 def _mainloop(self):
--> 479 EventLoop.idle()
480
D:\Anaconda\lib\site-packages\kivy\base.py in idle(self)
361 Logger.error('Base: Application will leave')
--> 362 self.exit()
363 return False
D:\Anaconda\lib\site-packages\kivy\base.py in exit(self)
374 '''Close the main loop and close the window.'''
--> 375 self.close()
376 if self.window:
D:\Anaconda\lib\site-packages\kivy\base.py in close(self)
171 self.quit = True
--> 172 self.stop()
173 self.status = 'closed'
D:\Anaconda\lib\site-packages\kivy\base.py in stop(self)
183 for provider in reversed(self.input_providers[:]):
--> 184 provider.stop()
185 if provider in self.input_providers_autoremove:
D:\Anaconda\lib\site-packages\kivy\input\providers\wm_pen.py in stop(self)
110 self.pen = None
--> 111 SetWindowLong_WndProc_wrapper(self.hwnd, self.old_windProc)
112
D:\Anaconda\lib\site-packages\kivy\input\providers\wm_common.py in _closure(hWnd, wndProc)
121 def _closure(hWnd, wndProc):
--> 122 oldAddr = func(hWnd, GWL_WNDPROC, cast(wndProc, c_void_p).value)
123 return cast(c_void_p(oldAddr), WNDPROC)
ArgumentError: argument 3: <class 'TypeError'>: wrong type
During handling of the above exception, another exception occurred:
ArgumentError Traceback (most recent call last)
D:\Anaconda\lib\site-packages\kivy\base.py in runTouchApp(widget, slave)
503 else:
--> 504 EventLoop.window.mainloop()
505 finally:
D:\Anaconda\lib\site-packages\kivy\core\window\window_sdl2.py in mainloop(self)
751
Please help me why doesn't it works?
Here is the example of working: https://kivy.org/doc/stable/guide/basic.html

How Can I Solve Encoding Problem while Using Kivy?

I am very new to establishing GUI's and Kivy, I am using Python 3. I have tried to run a basic code which I have found online but there seems to be an encoding issue which I couldn't solve. My code goes as:
import kivy
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text = "A")
if __name__ == "__main__":
MyApp().run()
The error message I get is this:
UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 280: character maps to undefined
Complete Traceback:
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-3-2a8b8f5ea334> in <module>
12
13
---> 14 MyApp().run()
C:\ProgramData\Anaconda3\lib\site-packages\kivy\app.py in run(self)
827 self.load_config()
828 self.load_kv(filename=self.kv_file)
--> 829 root = self.build()
830 if root:
831 self.root = root
<ipython-input-3-2a8b8f5ea334> in build(self)
9
10 def build(self):
---> 11 return Label(text='Hello world')
12
13
kivy\_event.pyx in kivy._event.EventDispatcher.__cinit__()
kivy\properties.pyx in kivy.properties.Property.link()
kivy\properties.pyx in kivy.properties.NumericProperty.init_storage()
kivy\properties.pyx in kivy.properties.Property.init_storage()
kivy\properties.pyx in kivy.properties.NumericProperty.convert()
kivy\properties.pyx in kivy.properties.NumericProperty.parse_str()
kivy\properties.pyx in kivy.properties.NumericProperty.parse_list()
kivy\properties.pyx in kivy.properties.dpi2px()
C:\ProgramData\Anaconda3\lib\site-packages\kivy\utils.py in __get__(self, inst, cls)
503 if inst is None:
504 return self
--> 505 retval = self.func(inst)
506 setattr(inst, self.func.__name__, retval)
507 return retval
C:\ProgramData\Anaconda3\lib\site-packages\kivy\metrics.py in dpi(self)
172 # for all other platforms..
173 from kivy.base import EventLoop
--> 174 EventLoop.ensure_window()
175 return EventLoop.window.dpi
176
C:\ProgramData\Anaconda3\lib\site-packages\kivy\base.py in ensure_window(self)
121 '''Ensure that we have a window.
122 '''
--> 123 import kivy.core.window # NOQA
124 if not self.window:
125 Logger.critical('App: Unable to get a Window, abort.')
C:\ProgramData\Anaconda3\lib\site-packages\kivy\core\window\__init__.py in <module>
2066 if platform == 'linux':
2067 window_impl += [('x11', 'window_x11', 'WindowX11')]
-> 2068 Window = core_select_lib('window', window_impl, True)
C:\ProgramData\Anaconda3\lib\site-packages\kivy\core\__init__.py in core_select_lib(category, llist, create_instance, base, basemodule)
101 'debug logging (e.g. add -d if running from the command line, or '
102 'change the log level in the config) and re-run your app to '
--> 103 'identify potential causes\n{1}'.format(category.capitalize(), err))
104
105
C:\ProgramData\Anaconda3\lib\logging\__init__.py in critical(self, msg, *args, **kwargs)
1428 """
1429 if self.isEnabledFor(CRITICAL):
-> 1430 self._log(CRITICAL, msg, args, **kwargs)
1431
1432 fatal = critical
C:\ProgramData\Anaconda3\lib\logging\__init__.py in _log(self, level, msg, args, exc_info, extra, stack_info)
1517 record = self.makeRecord(self.name, level, fn, lno, msg, args,
1518 exc_info, func, extra, sinfo)
-> 1519 self.handle(record)
1520
1521 def handle(self, record):
C:\ProgramData\Anaconda3\lib\logging\__init__.py in handle(self, record)
1527 """
1528 if (not self.disabled) and self.filter(record):
-> 1529 self.callHandlers(record)
1530
1531 def addHandler(self, hdlr):
C:\ProgramData\Anaconda3\lib\logging\__init__.py in callHandlers(self, record)
1589 found = found + 1
1590 if record.levelno >= hdlr.level:
-> 1591 hdlr.handle(record)
1592 if not c.propagate:
1593 c = None #break out
C:\ProgramData\Anaconda3\lib\logging\__init__.py in handle(self, record)
903 self.acquire()
904 try:
--> 905 self.emit(record)
906 finally:
907 self.release()
C:\ProgramData\Anaconda3\lib\site-packages\kivy\logger.py in emit(self, message)
245 self._write_message(_message)
246
--> 247 self._write_message(message)
248
249
C:\ProgramData\Anaconda3\lib\site-packages\kivy\logger.py in _write_message(self, record)
216 stream.write(fs % msg.encode("UTF-8"))
217 else:
--> 218 stream.write(fs % msg)
219 stream.flush()
220
C:\ProgramData\Anaconda3\lib\encodings\cp1252.py in encode(self, input, final)
17 class IncrementalEncoder(codecs.IncrementalEncoder):
18 def encode(self, input, final=False):
---> 19 return codecs.charmap_encode(input,self.errors,encoding_table)[0]
20
21 class IncrementalDecoder(codecs.IncrementalDecoder):
UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 280: character maps to <undefined>
```

what is the problem ?: application.connect() error

I am a beginner developer who started to study automation by using pywinauto.
An overflow error occurs when using application.connect () to connect to an already open program.
But application.start() works fine....
Please help me if someone know this part.
The source code and error contents are as follows.
Source code:
import pywinauto
app = pywinauto.application.Application()
app.connect(title_re='Calculator')
Error:
OverflowError Traceback (most recent call last)
in
1 import pywinauto
2 app = pywinauto.application.Application()
----> 3 app.connect(title_re='Calculator')
d:\Anaconda3\lib\site-packages\pywinauto\application.py in connect(self, **kwargs)
972 ).process_id
973 else:
--> 974 self.process = findwindows.find_element(**kwargs).process_id
975 connected = True
976
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_element(**kwargs)
82 so please see :py:func:find_elements for the full parameters description.
83 """
---> 84 elements = find_elements(**kwargs)
85
86 if not elements:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_elements(class_name, class_name_re, parent, process, title, title_re, top_level_only, visible_only, enabled_only, best_match, handle, ctrl_index, found_index, predicate_func, active_only, control_id, control_type, auto_id, framework_id, backend, depth)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in (.0)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in _title_match(w)
275 def _title_match(w):
276 """Match a window title to the regexp"""
--> 277 t = w.rich_text
278 if t is not None:
279 return title_regex.match(t)
d:\Anaconda3\lib\site-packages\pywinauto\win32_element_info.py in rich_text(self)
81 def rich_text(self):
82 """Return the text of the window"""
---> 83 return handleprops.text(self.handle)
84
85 name = rich_text
d:\Anaconda3\lib\site-packages\pywinauto\handleprops.py in text(handle)
86 length += 1
87
---> 88 buffer_ = ctypes.create_unicode_buffer(length)
89
90 ret = win32functions.SendMessage(
d:\Anaconda3\lib\ctypes_init_.py in create_unicode_buffer(init, size)
286 return buf
287 elif isinstance(init, int):
--> 288 buftype = c_wchar * init
289 buf = buftype()
290 return buf
OverflowError: cannot fit 'int' into an index-sized integer
import pywinauto
app = pywinauto.Application(backend='uia').start('calc.exe')
try this if you are having problem you have to say the backennd is a uia it working fine for me.

Categories

Resources