Kivy in Jypiter notebook: OSError: source code not available - python-3.x

Im̀ trying to create a code that uses kivy library to create a window that has a button as widget. To do that I used the following code copied from a online video so as far as I know it should work:
(Each running cell will be divided by some dots, as the first one runs with no problems but the second is where the error occures)
from kivy.app import App
from kivy.uix.button import Button
from kivy.interactive import InteractiveLauncher
from kivy.lang import Builder
#forzar a la app a no iniciar en pantalla completa
from kivy.config import Config
Config.set("graphics", "fullscreen", "0")
janela = None
glayout= None
...
class WindowApp(App):
pass
window = WindowApp()
wi = InteractiveLauncher(janela)
wi.run()
#the error that appears on the console after running the second cell goes like this:
[WARNING] [Deprecated ] Call to deprecated function __init__ in /home/alfred/anaconda3/envs/k39/lib/python3.10/site-packages/kivy/interactive.py line 308.Called from /tmp/ipykernel_5673/4179568724.py line 5 by <module>().
Exception in thread Thread-5 (startApp):
Traceback (most recent call last):
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
self.run()
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/site-packages/kivy/interactive.py", line 319, in startApp
app.run(*args, **kwargs)
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/site-packages/kivy/app.py", line 954, in run
self._run_prepare()
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/site-packages/kivy/app.py", line 923, in _run_prepare
self.load_kv(filename=self.kv_file)
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/site-packages/kivy/app.py", line 676, in load_kv
default_kv_directory = dirname(getfile(self.__class__))
File "/home/alfred/anaconda3/envs/k39/lib/python3.10/inspect.py", line 785, in getfile
raise OSError('source code not available')
OSError: source code not available
kvcode= """
FloatLayout:
Button:
size_hint: .1, .1
pos_hint: {"x":.3, "top": 1.}
text: "A"
"""
glayout= Builder.load_string(kvcode)
janela.root_window.add_widget(glayout)
After running the last cell a black window that crashes appears. So far Im quite new to using the Kivy library so Im̀ quite lost about what counld have gonne wrong since I've seen this code run without problems online.

Related

Pyinstaller "ValueError: Can't mix absolute and relative paths"

I am using windows 10 and anaconda3 to manage my python packages. This is my first time to use python, and I'm trying to make my own gui program with pyqt5. Also I'm trying to make .exe file using Pyinstaller. The issue I am running into is that the .exe is throwing the error block:
(pyqt5_env) C:\Python Projects>pyinstaller -w -F App_ver05.py
268 INFO: PyInstaller: 4.0.dev0+b3dd91c8a8
268 INFO: Python: 3.7.7 (conda)
268 INFO: Platform: Windows-10-10.0.18362-SP0
Traceback (most recent call last):
File "c:\anaconda3\envs\pyqt5_env\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\anaconda3\envs\pyqt5_env\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\envs\pyqt5_env\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
File "c:\anaconda3\envs\pyqt5_env\lib\site-packages\PyInstaller\__main__.py", line 112, in run
spec_file = run_makespec(**vars(args))
File "c:\anaconda3\envs\pyqt5_env\lib\site-packages\PyInstaller\__main__.py", line 58, in run_makespec
spec_file = PyInstaller.building.makespec.main(filenames, **opts)
File "c:\anaconda3\envs\pyqt5_env\lib\site-packages\PyInstaller\building\makespec.py", line 458, in main
specfile.write(onefiletmplt % d)
File "c:\anaconda3\envs\pyqt5_env\lib\site-packages\PyInstaller\building\makespec.py", line 101, in __repr__
self.variable_prefix, self.filename_suffix = make_variable_path(self.path)
File "c:\anaconda3\envs\pyqt5_env\lib\site-packages\PyInstaller\building\makespec.py", line 84, in make_variable_path
if os.path.commonpath([filename, from_path]) == from_path:
File "c:\anaconda3\envs\pyqt5_env\lib\ntpath.py", line 615, in commonpath
raise ValueError("Can't mix absolute and relative paths") from None
ValueError: Can't mix absolute and relative paths
The same error occurs regardless of which .py file is used. For information, I wrote the used code below.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn1 = QPushButton('&Button1', self)
btn1.setCheckable(True)
btn1.toggle()
vbox = QVBoxLayout()
vbox.addWidget(btn1)
self.setLayout(vbox)
self.setWindowTitle('QPushButton')
self.setGeometry(300, 300, 300, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
I uninstalled and reinstalled pyinstaller but it didn't work. I don't think its a code issue because the code is really simple. Can anyone give a solution or hint for this problem?
What happened for me is that the absolute path name had a space in it. Once the project was moved to a directory without spaces it was able to build
The solution of this problem is to use the full file name and append the flag -F to the file name. In your case for example if for the file App_ver05.py the absolute path is :
/home/user123/Desktop/foldername/App_ver05.py
Then use the command :
pyinstaller -F /home/user123/Desktop/foldername/App_ver05.py

python tkinter non blocking information

I am trying to create non-blocking tkiner messagebox using multithreading. I know messagebox is not defined in this way, but I preferred the messagebox concept and functions. I am having actual main program which is quite large and complex so showing some example
program toto.py
import threading
from disp_message import disp_message
msg =" This is a test message"
msgtype = 1
t1 = threading.Thread(target=disp_message, args=(msg,msgtype,))
t1.start()
t1.join()
for i in range(100000):
print(i)
disp_message(msg,msgtype)
print("Done!")
disp_messagee python function code in another file
from tkinter import *
from tkinter import messagebox
def disp_message(msg,msgtype):
top = Tk()
top.withdraw()
if msgtype==1:
messagebox.showwarning("Warning",msg)
elif msgtype==2:
messagebox.showinfo("information",msg)
else:
messagebox.showerror("Error",msg)
When I run this program i am having 2 issues
1. Following error
Traceback (most recent call last):
File "toto.py", line 13, in <module>
disp_message(msg,msgtype)
File "c:\NSE\scripts\disp_message.py", line 8, in disp_message
messagebox.showwarning("Warning",msg)
File "C:\ProgramData\Anaconda\lib\tkinter\messagebox.py", line 87, in showwarning
return _show(title, message, WARNING, OK, **options)
File "C:\ProgramData\Anaconda\lib\tkinter\messagebox.py", line 72, in _show
res = Message(**options).show()
File "C:\ProgramData\Anaconda\lib\tkinter\commondialog.py", line 39, in show
w = Frame(self.master)
File "C:\ProgramData\Anaconda\lib\tkinter\__init__.py", line 2744, in __init__
Widget.__init__(self, master, 'frame', cnf, {}, extra)
File "C:\ProgramData\Anaconda\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
RuntimeError: main thread is not in main loop
Secondly it displays messagebox and wait for acknowledgement.
While my objective is to display messagebox and parallel let program get executed and finished.
Can you pl help ?

Python Code with Plugin "Create Points Layer from Spreadsheet"

I'm new to python, that is the first problem.
Secondly I am trying to automate the task of adding vector point layers from spreadsheets (xlsx-files) with Python.
The task can be done manually with the plugin "add spreadsheet layer".
I have a folder with roughly 20 xlsx-files that need to be added into the QGIS-project as vector point layers.
I have tried the following code snippet, to check if the core task of adding a spreadsheet layer actually works:
The Computer has a Win7 OS. The program in question is Python which is contained in the program QGIS 3.4.
The Plugin that I want to control through python is called "add spreadsheet layer".
from qgis.core import *
import processing
processing.run("qgis:createpointslayerfromtable",
{'INPUT':r'C:\Users\Desktop\PlayItAll\Test.xlsx',
'XFIELD':'X_Pos',
'YFIELD':'Y_Pos',
'ZFIELD':None,
'MFIELD':None,
'TARGET_CRS':QgsCoordinateReferenceSystem('EPSG:4326'),
'OUTPUT':r'memory'})
It produces this error:
File "C:/PROGRA1/QGIS31.4/apps/qgis/./python/plugins\processing\core\Processing.py", line 183, in runAlgorithm
raise QgsProcessingException(msg)
I have contacted the programmer of the plugin and he gave me this code to try:
import processing
processing.runAndLoadResults("qgis:createpointslayerfromtable",
{
'INPUT':r'C:\Users\username\Desktop\Delete\test.xlsx',
'XFIELD':'Longitude',
'YFIELD':'Latitude',
'ZFIELD':None,
'MFIELD':None,
'TARGET_CRS':QgsCoordinateReferenceSystem('EPSG:4326'),
'OUTPUT':'memory'
})
For him it worked, for me it didn't.
I got this on the processing tab:
2019-07-03T13:19:43 CRITICAL Traceback (most recent call last):
File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python/plugins\processing\algs\qgis\PointsLayerFromTable.py", line 112, in processAlgorithm
fields, wkb_type, target_crs)
Exception: unknown
2019-07-03T13:19:43 CRITICAL Traceback (most recent call last):
File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python/plugins\processing\algs\qgis\PointsLayerFromTable.py", line 112, in processAlgorithm
fields, wkb_type, target_crs)
Exception: unknown
2019-07-03T13:19:43 CRITICAL There were errors executing the algorithm.
The "python warnings" tab showed this:
2019-07-03T13:19:43 WARNING warning:__console__:1: ResourceWarning:
unclosed file
traceback: File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python\console\console.py", line 575, in runScriptEditor
self.tabEditorWidget.currentWidget().newEditor.runScriptCode()
File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python\console\console_editor.py", line 629, in runScriptCode
.format(filename.replace("\\", "/"), sys.getfilesystemencoding()))
File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python\console\console_sci.py", line 635, in runCommand
more = self.runsource(src)
File "C:/PROGRA~1/QGIS3~1.4/apps/qgis/./python\console\console_sci.py", line 665, in runsource
return super(ShellScintilla, self).runsource(source, filename, symbol)
File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 74, in runsource
self.runcode(code)
File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in

How can solve error in autopytoexe to compile python program to exe?

when I try to compile program in python 3.7
with:
auto-py-to-exe v2.6.0
Selenium
The code is:
from selenium import webdriver
import pathlib
import resource
fn = pathlib.Path(__file__).parent / 'chromedriver.exe'
browser = webdriver.Chrome(fn)
browser.get('website')
# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')
password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')
nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()
browser.get('website')
nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()
nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()
nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()
error in compile
An error occurred, traceback follows:
Traceback (most recent call last):
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\auto_py_to_exe-2.6.0-py3.7.egg\auto_py_to_exe\__main__.py", line 259, in convert
pyi.run() # Execute PyInstaller
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 111, in run
run_build(pyi_config, spec_file, **vars(args))
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
exec(text, spec_namespace)
File "<string>", line 29, in <module>
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 424, in __init__
strip_binaries=self.strip, upx_binaries=self.upx,
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 196, in __init__
self.__postinit__()
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
self.assemble()
File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 273, in assemble
pylib_name = os.path.basename(bindepend.get_python_library_path())
File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 214, in basename
return split(p)[1]
File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 183, in split
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType
all log
i expect correct compile
i try
install windows sdk
install visual c++ libraries
need help to resolve the problem
this is the code from my python program
One problem with your code is that you are trying to load chromedriver.exe which can be found in your current directory but after freezing it cannot be loaded anymore. When you want to freeze your app with Pyinstaller you first need to add that file to your output executable and then load it from the temp directory.
I'm not sure about auto-py-to-exe but you can use the below code and then use
pyinstaller -F --add-data "chromedriver.exe;." yourscript.py
from selenium import webdriver
import resource
import sys
import os
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
fn = resource_path('chromedriver.exe')
browser = webdriver.Chrome(fn)
browser.get('website')
# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')
password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')
nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()
browser.get('website')
nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()
nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()
nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()
Solved in the simplest way, pass the proyect folder with the script to
  disk C: and the errors were solved gave error while it was saved in disk E:

Flask-DebugToolbar not working with mongoDB

I am tying to use Flask-MongoEngine which is working fine, but I am trying to get the debug toolbar to work and when I follow the documentation I get a traceback shown below. I am able to run the normal flask debug toolbar fine but since I am using MongoDB as the database I am trying to use the flask debug toolbar with MongoDB. I know that the following line is the cause of this traceback `
app.config['DEBUG_TB_PANELS'] = ['flask_mongoengine.panels.MongoDebugPanel']
example code
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.config['DEBUG_TB_PANELS'] = ['flask_mongoengine.panels.MongoDebugPanel']
db = MongoEngine(app)
toolbar = DebugToolbarExtension(app)
line that causes traceback
app.config['DEBUG_TB_PANELS'] = ['flask_mongoengine.panels.MongoDebugPanel']
#traceback
Traceback (most recent call last):
File "app.py", line 27, in <module>
toolbar = DebugToolbarExtension(app)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_debugtoolbar/__init__.py", line 58, in __init__
self.init_app(app)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_debugtoolbar/__init__.py", line 72, in init_app
DebugToolbar.load_panels(app)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_debugtoolbar/toolbar.py", line 50, in load_panels
for panel_class in cls._iter_panels(app):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_debugtoolbar/toolbar.py", line 57, in _iter_panels
panel_class = cls._import_panel(app, panel_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_debugtoolbar/toolbar.py", line 71, in _import_panel
panel_class = import_string(path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/werkzeug/utils.py", line 418, in import_string
__import__(import_name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_mongoengine/panels.py", line 5, in <module>
from flask_mongoengine import operation_tracker
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask_mongoengine/operation_tracker.py", line 26, in <module>
'_unpack_response': pymongo.helpers._unpack_response,
AttributeError: module 'pymongo.helpers' has no attribute '_unpack_response'
The _unpack_respone method seems to be gone or rewritten since pymongo 3.6.0.
A workaround is to install pymongo<3.6.0

Resources