I have a created test file, test_sample.py. In that file I am trying to import the matplotlip package matplotlib.backends.backend_qt5agg, while running the pytest command it shows the following error. When I comment that import line, the pytest command will run successfully. But I should import that line.
test_sample.py file,
from PyQt5 import QtCore, QtGui, QtTest, QtWidgets
from PyQt5.QtCore import QCoreApplication, QObject, Qt
from PyQt5.QtWidgets import *
from pytestqt.plugin import QtBot
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
def test_method(self):
--------------
all the code
----------------
The following error,
test_sample.py:8: in <module>
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt5agg.py:7: in <module>
from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611
..\esd_env\lib\site-packages\matplotlib\backends\backend_qtagg.py:12: in <module>
from .backend_qt import QtCore, QtGui, _BackendQT, FigureCanvasQT
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt.py:72: in <module>
_MODIFIER_KEYS = [
..\esd_env\lib\site-packages\matplotlib\backends\backend_qt.py:73: in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
E TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
I don't know why it end up with this error. This import works successfully when I run the application. It cause an error only on running testcases using commandpytest.
Note I have installed matplotlip==3.6.0
Kindly help me to fix this issue.
Related
Problem
I have written a code that takes some historical data as input. Assuming dataset has a timeseries format, I am trying to do a regression and find a predictor.
Code
For my project, I have four files: my_project.py, utilities.py, plotter.py, and constants.py. Here is some small portions (relevant imports) of the two scripts:
my_project.py:
from time import perf_counter
from constants import (output_dir, DATAPATH, output_file)
from utilities import (dataframe_in_nutshell, excel_reader, info_printer, sys, module_creator, process_discovery, data_explanatory_analysis, excel_reader, df_cleaner, feature_extractor, ml_modelling)
from plotter import Plotter
utilities.py
import os
import sys
import inspect
from pathlib import Path
from typing import (Iterable, List, Tuple, Optional)
from itertools import zip_longest
import matplotlib.pyplot as plt
import statsmodels.tsa.api as smt
import statsmodels.api as sm
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import scale
from pycaret.regression import (setup, compare_models, predict_model, plot_model, finalize_model, load_model)
import csv
from constants import (np, Path, nan_value, plots_dir, HOURS_PER_WEEK, LAGS_STEP_NUM, rc_params, NA_VALUES, COLUMNS_NAMES, string_columns, LAGS_LABELS, numeric_columns, output_dir, DATAPATH, dtype_dict, train_size)
from pprint import PrettyPrinter
pp = PrettyPrinter()
import seaborn as sns
sns.set()
Error Message
Traceback (most recent call last):
File "c:\Users\username\OneDrive\Desktop\project\my_project.py", line 10, in <module>
from utilities import (dataframe_in_nutshell, excel_reader, info_printer, sys, module_creator,
File "c:\Users\username\OneDrive\Desktop\project\utilities.py", line 18, in <module>
from pycaret.regression import (setup, compare_models, predict_model, plot_model, finalize_model,
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\regression.py", line 10, in <module>
import pycaret.internal.tabular
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\internal\tabular.py", line 48, in <module>
import pycaret.internal.preprocess
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pycaret\internal\preprocess.py", line 27, in <module>
from pyod.models.knn import KNN
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\__init__.py", line 4, in <module>
from . import utils
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\utils\__init__.py", line 4, in <module>
from .stat_models import pairwise_distances_no_broadcast
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\pyod\utils\stat_models.py", line 11, in <module>
from numba import njit
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\__init__.py", line 42, in <module>
from numba.np.ufunc import (vectorize, guvectorize, threading_layer,
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\np\ufunc\__init__.py", line 3, in <module>
from numba.np.ufunc.decorators import Vectorize, GUVectorize, vectorize, guvectorize
File "C:\Users\username\anaconda3\envs\py310\lib\site-packages\numba\np\ufunc\decorators.py", line 3, in <module>
from numba.np.ufunc import _internal
SystemError: initialization of _internal failed without raising an exception
Logistics
I am running my_project.py in visual studio code on a Windows 10 machine.
All packages are based on Python 3.10 using conda-forge channel
Research
The following pages seem to explain a workaround but I am not sure if I am understanding the issue in here. I would appreciate if you can help me figure this out.
Error on import with numpy HEAD
Update ufunc loop signature resolution to use NumPy
Remove reliance on npy_ ufunc loops.
I had this very same issue today.
Solved it by downgrading Numpy to 1.23.1
So: pip install numpy==1.23.1
I have a problem with Selenium.
def main_test():
chrome_options = Options()
prefs = {"download.default_directory": f"{os.getcwd()}/Music"}
chrome_options.add_argument("user-data-dir=selenium")
chrome_options.add_experimental_option("prefs", prefs)
dr = webdriver.Chrome(options=chrome_options, service=Service(ChromeDriverManager().install()))
dr.get(URL)
print(f"{selenium.__version__=}")
dr.find_element(By.XPATH, "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()
dr.quit()
if __name__ == '__main__':
main_test()
This is my code. I think i followed properly the documentation. Although, when running the app i get this error:
selenium.__version__='4.6.0'
Traceback (most recent call last):
File "/Users/andrea/Dev/Python/custom_scripts/ytchannel/main.py", line 142, in <module>
main_test()
File "/Users/andrea/Dev/Python/custom_scripts/ytchannel/main.py", line 137, in main_test
dr.find_element(By.XPATH, "/html/body/div[1]/div[1]/div/div[1]/ul/li[2]/a").click()
AttributeError: type object 'By' has no attribute 'XPATH'
I have no clue on what i'm doing wrong...
I can add every detail possible if needed.
EDIT:
Here my imports:
import socket
import httpcore
import re
import os
import json
import selenium
import httpx as web
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from time import sleep
Your code looks correct.
Make sure you imported the By properly.
This import should be used:
from selenium.webdriver.common.by import By
After the installation of market calendar, when I import:
import pandas_market_calendars
I get following error:
ImportError: cannot import name 'apply_wraps' from 'pandas._libs.tslibs.offsets'
import pandas as pd
import pandas_market_calendars as mcal
I've a problem with the importations of modules in Python. I'm doing a project with PyQt and I'm trying to refactor and restructure it.
The hierarchy is the next:
./main.py
./logic/__init__.py
./logic/transforms.py
./logic/hopfield.py
./gui/__init__.py
./gui/interface.py
./gui/mplwidget.py
./img
The error:
Traceback (most recent call last):
File "...\main.py", line 5, in <module>
from gui.interface import Ui_MainWindow
File ...\gui\interface.py", line 215, in <module>
from mplwidget import MplWidget
ModuleNotFoundError: No module named 'mplwidget'
The file interface.py
class Ui_MainWindow(object):
.
.
.
from mplwidget import MplWidget
The file main.py
import sys
import matplotlib
import numpy as np
from gui.interface import Ui_MainWindow
from gui.weightMatrix import Ui_Dialog
from gui.table import TableModel
from logic.hopfield import learn, searchPattern
from logic.transforms import transformVector, transformVectors
from PyQt5 import QtCore, QtGui, QtWidgets
class Actions(Ui_MainWindow):
def __init__(self):
.
.
.
I don't understand why it doesn't work, since inside the module if I run the interface file it works fine together with mplwidget as a module.
File ...\gui\interface.py", line 215, in
from mplwidget import MplWidget
your interface.py should have
absolute import:
from gui.mplwidget import MplWidget
or
relative import:
from .mplwidget import MplWidget
In addition, a great blog that explains the two different imports
Been playing around with pyinstaller and cx_freeze the last couple of days trying to get my app to run as a .exe.
In python everything works as intended.
I have the following items in a folder ready for compile...
rawCodes.py is my main.
mcnc.py is my PyQt5 GUI.
mcnclogo_rc.py contains all the images i used in my GUI.
The following is a list of my imports in my main...
import sqlite3
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
It seems that when i run pyinstaller it completes the process and produces 3 folders as expected.
The exe is clearly inside the dist folder and all appears to have worked.
However i run the exe and it just opens then closes again and nothing comes up.
I am convinced that my mcnc.py file is not being included and therefore i am not seeing a GUI (pyqt5).
Does anyone know how to specifically list mcnc.py in my SPEC file to make sure it is included...same with mcnclogo_rc.
EDIT
I have run the .exe from CMD and i am getting the following traceback...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
Traceback (most recent call last):
File "rawCodes.py", line 3287, in <module>
File "rawCodes.py", line 22, in __init__
File "rawCodes.py", line 3101, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[13020] Failed to execute script rawCodes
Could it be that my database isnt getting packed properly in to the dist/build?
EDIT 2
I have changed the sqlite3 pathing so it is dynamic however it is still giving exactly the same error...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
package_dir = os.path.abspath(os.path.dirname(__file__))
db_dir = os.path.join(package_dir, 'codes.db')
print(db_dir)
conn = sqlite3.connect(db_dir)
c = conn.cursor()
c.execute('')
def stainless_list(self):
stainless_getlist = []
content = 'SELECT grade FROM stainless ORDER BY prefix ASC'
res = conn.execute(content)
for row in res:
stainless_getlist.append(row[0])
conn.close
stainless_getlist.insert(0, "Select...")
self.comboBox_2.clear()
self.comboBox_2.addItems(stainless_getlist)
#print(stainless_getlist)
return
Then i still get the following error...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
Traceback (most recent call last):
File "rawCodes.py", line 3287, in <module>
File "rawCodes.py", line 22, in __init__
File "rawCodes.py", line 3101, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[14664] Failed to execute script rawCodes
EDIT 3
Here is the print of my dir paths once compiled...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes\codes.db
Here is my code and imports...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
import os.path as op
try:
this_file = __file__
except NameError:
this_file = sys.argv[0]
this_file = op.abspath(this_file)
if getattr(sys, 'frozen', False):
application_path = getattr(sys, '_MEIPASS',
op.dirname(sys.executable))
else:
application_path = op.dirname(this_file)
sqlite_conn = os.path.join(application_path, 'codes.db')
print(application_path)
print(sqlite_conn)
conn = sqlite3.connect(sqlite_conn)
c = conn.cursor()
c.execute('')
but once compiled and trying to run from the dist it can no longer see the tables in the db.
EDIT 4
I changed my code to the following...
import sqlite3
import mcnc
from mcnc import Ui_MainWindow
import mcnclogo_rc
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem,
QDialog, QComboBox
import sys
import math
import os
import os.path as op
try:
this_file = __file__
except NameError:
this_file = sys.argv[0]
this_file = op.abspath(this_file)
if getattr(sys, 'frozen', False):
application_path = getattr(sys, '_MEIPASS', op.dirname(sys.executable))
else:
application_path = op.dirname(this_file)
sqlite_conn = os.path.join(QApplication.applicationDirPath(), 'codes.db')
print(application_path)
print(sqlite_conn)
conn = sqlite3.connect(sqlite_conn)
c = conn.cursor()
c.execute('')
I now get the following traceback...
G:\Yans work in progress\Yans python\Qt\to
compile\dist\rawCodes>rawCodes.exe
QCoreApplication::applicationDirPath: Please instantiate the QApplication
object first
G:\Yans work in progress\Yans python\Qt\to compile\dist\rawCodes
codes.db
Traceback (most recent call last):
File "rawCodes.py", line 3303, in <module>
File "rawCodes.py", line 38, in __init__
File "rawCodes.py", line 3117, in Load_StainlessDb
sqlite3.OperationalError: no such table: stainless
[3268] Failed to execute script rawCodes
EDIT 5
app = QApplication(sys.argv)
sqlite_conn = os.path.join(QApplication.applicationDirPath(), 'codes.db')
G:\Yans work in progress\Yans python\Qt
C:/Program Files (x86)/Python37-32\codes.db
Got a straight up error and couldnt connect to the db at all.
The db folder now points to C: drive.
After many hours i noticed that the script was failing at the point where it tried to access the tables of the db and not at the connect statement in my compile.
Upon further inspection i noticed that after the compile has run the codes.db was missing until i clicked the .exe to run. Then a codes.db popped out of the exe with 0kb and no tables.
I have concluded that i need to research how to include the original .db file in the compile and not allow it to create a new empty .db in its absence.
I have tested this by over writing the empty .db with the original .db and suddenly my .exe works perfectly.
I believe the answer is simple. Let's analyse the stacktrace
The red part is the error name: OperationalError. From the docs:
Exception raised for errors that are related to the database’s operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, etc. It is a subclass of DatabaseError.
But, the green part tells us:
no such table: stainless
which simply means the table is not found as it was either deleted or it was not created at all.
And, as far as i can see, no table creation code is to be found. It's not a PyInstaller error.
Your exe closes then opens up because you have no body code. In your main code's body add this:
input()
That should fix it.