how to access variable from another class in python - class

I would like to access variable lotId & qty_selected in class 'InputDialog' and to be use in class 'Mainwindow'. I did tried to find a solution in net but unable to solve it until now. can anyone show how to make it?
Here is my current code:
from __future__ import division
from skimage.measure import compare_ssim as ssim
import matplotlib.pyplot as plt
import numpy as np
import sys
import os, glob
import cv2
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from inputdialog import Ui_inputDialog
from mainwindow import Ui_mainWindow
from tkinter import messagebox
class MainWindow(QtGui.QMainWindow, Ui_mainWindow):
def __init__(self, class_input):
QtGui.QMainWindow.__init__(self)
Ui_mainWindow.__init__(self)
Ui_inputDialog.__init__(self)
self.setupUi(self)
self.capture_button.clicked.connect(self.captureImage)
self.display_button.clicked.connect(self.displayImage)
self.deviceBox.activated.connect(self.selectDeviceCombo)
self.startInspectionBtn.clicked.connect(self.enterLotID)
self.display_button.clicked.connect(self.displayResults)
#self.viewResultBtn.clicked.connect(self.viewResults)
self.window2 = None
def enterLotID(self): # Dialog box will ask user to enter lot ID and wafer qty
if self.window2 is None:
self.window2 = InputDialog(self)
self.window2.isModal()
self.window2.show()
# Program need to be loop through a image file in directory
def displayImage(self, ):
os.chdir('c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId )
for lotId in glob.glob('*.jpeg'):
print(lotId)
sample_label = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 6.jpg' # Sample image must read from current folder lot ID running the inspection
self.sample_label.setScaledContents(True)
self.sample_label.setPixmap(QtGui.QPixmap(sample_label))
def selectDeviceCombo(self):
self.var_Selected = self.deviceBox.currentText()
#print('The user selected value now is:')
print('Device = ' + self.var_Selected)
if self.var_Selected.lower() == 'xf35':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 4.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'xf38':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 5.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'x38c':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
else:
print("Pls select device id. It's compulsory field!")
def captureImage(self): # Capture image and display on 'Sample' column under Inspection
cam = cv2.VideoCapture(0)
i = 1
while i < int(input(qty_selected)):
ret, frame = cam.read()
cv2.imshow('Please review an image', frame)
if not ret:
break
k = cv2.waitKey(0)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
if k % 256 == 32:
# SPACE pressed
img_name = "_{}.jpeg".format(i)
#print (img_name)
cv2.imwrite(img_name, frame)
#cv2.imwrite(os.path.join(dirname, img_name), frame)
print("{}".format(img_name))
i += 1
cam.release()
cv2.destroyAllWindows()
def displayResults(self): #Display image of wafer at 'Result' tab. Simultaneously with 'Inspect'
label_vid01 = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.label_vid01.setScaledContents(True)
self.label_vid01.setPixmap(QtGui.QPixmap(label_vid01))
# A new class for user input dialog to enter lot information
class InputDialog (QtGui.QDialog, Ui_inputDialog):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.okButton.clicked.connect(self.addLotId)
self.okButton.clicked.connect(self.selectWaferQty)
def addLotId(self):
lotId = str(self.strLotId.toPlainText())
self.strLotId.setText(lotId)
print(lotId)
path = 'c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId
if not os.path.exists(path):
os.makedirs(path)
else:
messagebox.showwarning('Error','Please enter required information')
QtGui.QMessageBox.show(self)
# User require to select wafer quantity upon enter the lot ID
def selectWaferQty(self):
qty_selected = self.waferQty.currentText()
#print ('The user selected value now is:')
print ('Wafer Qty = ' + qty_selected)
#if self.qty_selected() == '1':
# print('Great! Wafer Qty is - ' + self.qty_selected + '!')
#else:
# print ('Pls select wafer quantity!')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
Window = MainWindow()
Window.show()
sys.exit()

Under the class InputDialog, change lotId and qty_selected to self.lotId and self.qty_selected, respectively. And to access it inside your WindowMain class, try self.window2.lotId and self.window2.qty_selected.

Related

object has no attribute 'dlg'

I'm trying to create a plugin for a Uni-subject which will receive a zipcode from a user and return the name of the corresponding location.
I have created the plugin layout, through the Plugin Builder and have designed the graphical interface with QtDesigner https://i.stack.imgur.com/h6k6Q.png . I have also added the .txt file that contains the zipcodes database to the plugin folder.
However, when I reload the plugin it gives me the error "object has no attribute 'dlg'" error message
Could you give me some guidance here and point me to where the problem could be? I am new to plugin development and python. Thanks
The code is this one:
import os
import sys
import qgis.core
from qgis.PyQt import uic
from qgis.PyQt import (
QtCore,
QtWidgets
)
import geocoder
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'example_dialog_base.ui'))
class ExampleDialog(QtWidgets.QDialog, FORM_CLASS):
POSTAL_CODES_PATH = ":/plugins/example/todos_cp.txt"
def __init__(self, parent=None):
"""Constructor."""
super(ExampleDialog, self).__init__(parent)
# Set up the user interface from Designer through FORM_CLASS.
# After self.setupUi() you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
#self.QpushButton.clicked.connect(self.print_hello_world)
self.QlineEdit.textChanged.connect(self.toggle_find_button)
self.find_code_btn.clicked.connect(self.execute)
#def print_hello_world(self):
#print('Hello World!')
def toggle_find_button(self):
if self.QlineEdit.text() == "":
self.find_code_btn.setEnabled(False)
else:
self.find_code_btn.setEnabled(True)
def find_record(self, main_code, extension):
file_handler = QtCore.QFile(self.POSTAL_CODES_PATH)
file_handler.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file_handler)
while not stream.atEnd():
line = stream.readLine()
info = line.split(";")
code1 = info[-3]
code2 = info[-2]
if code1 == main_code and code2 == extension:
result = info
break
else:
raise RuntimeError("Sem resultados")
return result
def handle_layer_creation(self, record):
place_name = record[3]
point = geocode_place_name(place_name)
print("lon: {} - lat: {}".format(point.x(), point.y()))
layer = create_point_layer(
point,
f"found_location_for_{record[-3]}_{record[-2]}",
place_name
)
current_project = qgis.core.QgsProject.instance()
current_project.addMapLayer(layer)
def show_error(self, message):
message_bar = self.iface.messageBar()
message_bar.pushMessage("Error", message, level=message_bar.Critical)
def validate_postal_code(raw_postal_code):
code1, code2 = raw_postal_code.partition("-")[::2]
if code1 == "" or code2 == "":
raise ValueError(
"Incorrect postal code: {!r}".format(raw_postal_code))
return code1, code2
def geocode_place_name(place_name):
geocoder_object = geocoder.osm(place_name)
lon = geocoder_object.json.get("lng")
lat = geocoder_object.json.get("lat")
if lat is None or lon is None:
raise RuntimeError(
"Could not retrieve lon/lat for "
"place: {!r}".format(place_name)
)
point = qgis.core.QgsPointXY(lon, lat)
return point
def create_point_layer(point, layer_name, place_name):
layer = qgis.core.QgsVectorLayer(
"Point?crs=epsg:4326&field=address:string(100)",
layer_name,
"memory"
)
provider = layer.dataProvider()
geometry = qgis.core.QgsGeometry.fromPointXY(point)
feature = qgis.core.QgsFeature()
feature.setGeometry(geometry)
feature.setAttributes([place_name])
provider.addFeatures([feature])
layer.updateExtents()
return layer

persistent issue with PyQt6 QtWebEngine

In Chrome, if you close the pop up dialog of this page, then it won't show if you open the page again. However, in my following code, the pop up dialog still shows in a second run even you close it in the first run, it seems to be a issue with the persistent storage, but I don't know how to solve the issue, any help?
from PyQt6.QtCore import *
from PyQt6.QtCore import pyqtSlot as Slot
from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtWebEngineWidgets import *
from PyQt6.QtWebEngineCore import *
import sys
import os
class WebEngineView(QWebEngineView): # QWebEngineView
def __init__(self, parent=None):
super().__init__(parent)
self.webpage = QWebEnginePage()
# self.webpage.javaScriptConsoleMessage = lambda level, message, lineNumber, sourceID: print(message) # if level > QWebEnginePage.WarningMessageLevel else None # 关闭js console msg,不起作用→self.javaScriptConsoleMessage = None;https://doc.qt.io/qt-5/qwebenginepage.html#JavaScriptConsoleMessageLevel-enum
self.setPage(self.webpage)
self.webpage.load(QUrl('https://fanyi.baidu.com/'))
if __name__ == "__main__":
app = QApplication(sys.argv)
webEngineView = WebEngineView()
webEngineView.showMaximized()
sys.exit(app.exec())
My solotion:
from PyQt6.QtCore import *
from PyQt6.QtCore import pyqtSlot as Slot
from PyQt6.QtCore import pyqtSignal as Signal
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from PyQt6.QtWebEngineWidgets import *
from PyQt6.QtWebEngineCore import *
import sys
import os
class WebEnginePage(QWebEnginePage): # QWebEngineView
def __init__(self, profile, parent=None):
super().__init__(profile, parent)
def contextMenuEvent(self, event): # 算是一种折中的方法,因为其他的方法好像因为bug的原因不起作用
self.menu = self.createStandardContextMenu() # page().
selectedText = self.selectedText()
if selectedText:
self.menu.addSeparator()
self.menu.addAction('谷歌搜索', lambda: QDesktopServices.openUrl(QUrl(f'https://www.google.com/search?q={selectedText}')))
self.menu.popup(event.globalPos()) # 这种貌似怪异的做法也不能改成show或pos;using menu.exec() might lead to consolle warnings and painting artifacts, so using popup() is better
class WebEngineView(QWebEngineView): # QWebEngineView
def __init__(self, parent=None):
super().__init__(parent)
self.webEngineProfile = QWebEngineProfile('EngkudictWebEngineProfile ')
# self.webEngineProfile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)
print(self.webEngineProfile.persistentCookiesPolicy(), self.webEngineProfile.isOffTheRecord())
self.webpage = WebEnginePage(self.webEngineProfile) # QWebEnginePage(self.webEngineProfile)
# self.webpage.destroyed.connect(lambda obj: self.webEngineProfile.deleteLater()) #这种方式不行 If the profile is not the default profile, the caller must ensure that the profile stays alive for as long as the page does.
self.setPage(self.webpage)
self.webpage.load(QUrl('https://fanyi.baidu.com/'))
# webEngineProfile = self.page().profile()
# # webEngineProfile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)
# print(webEngineProfile.persistentCookiesPolicy(), webEngineProfile.isOffTheRecord(), webEngineProfile.persistentStoragePath()) # Qt6 PersistentCookiesPolicy.NoPersistentCookies True=====Qt6 1 False
# # self.load(QUrl('https://fanyi.baidu.com/'))
# self.load(QUrl('https://doc.qt.io/qt-6/qwebengineprofile.html#QWebEngineProfile-1'))
#Slot(QCloseEvent)
def closeEvent(self, event):
self.setPage(None) # To avoid msg: Release of profile requested but WebEnginePage still not deleted. Expect troubles ! https://github.com/qutebrowser/qutebrowser/commit/e6ae8797e71a678bef97a13b9057e29442e0ef48
# del self.webEngineProfile
# self.webEngineProfile.deleteLater() # A disk-based QWebEngineProfile should be destroyed on or before application exit, otherwise the cache and persistent data may not be fully flushed to disk. https://doc.qt.io/qt-6/qwebengineprofile.html#QWebEngineProfile-1
if __name__ == "__main__":
# QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # 任务Qt6 不需要了Qt High DPI scaling is now activated by default; the default rounding policy is PassThrough
# os.putenv("QT_ENABLE_HIGHDPI_SCALING", '1')
os.putenv("QT_SCALE_FACTOR", '1.6')
app = QApplication(sys.argv)
webEngineView = WebEngineView()
webEngineView.showMaximized()
sys.exit(app.exec())

Integration of Locust with Pytest

I am trying to integrate pytest and locust and facing the issue PytestCollectionWarning: cannot collect test class because it has a init constructor
import json
import pytest
import requests
from locust import SequentialTaskSet, task
request_url = ""
module_name = "shifts"
class TestShifts(SequentialTaskSet):
def get_shifts_data(self, login, request_data):
global request_url
name = "Get Shifts Data"
request_url = login.get_base_url() + request_data['path']
with self.client.get(request_url, catch_response=True, name=name, headers=login.get_header_get_request()) \
as get_shift_response:
if get_shift_response.status_code == 200:
get_shift_response.success()
return json.loads(get_shift_response.content)
else:
get_shift_response.failure("Get Shifts Failure")
#pytest.mark.usefixtures("login", "request_data")
def test_delete_shift(self, login, request_data):
global request_url
name = "Delete Shift with name :" + request_data['requestBody']['name']
shifts_data_dict = self.get_shifts_data(login, request_data)
for shift in shifts_data_dict['shifts']:
if shift['name'] == request_data['requestBody']['name']:
with self.client.delete(request_url + "/" + shift['id'], catch_response=True, name=name,
headers=login.get_header_get_request()) as shift_delete_response:
if shift_delete_response.status_code == 204:
shift_delete_response.success()
else:
shift_delete_response.failure("Shift Delete Failure")

why excel process stay opened after printing

i use these packages:
openpyxl - copy excel templates, opened copied file, save data from db, print it and then delete;
pywin32 - send for printing to remote network printer by network name;
after some processes, i don't know which - excel process window still opened. (attach screenshot)
i attach the most using in my project functions.
this program it's like a web service, which listening 5000 port and print in needed template.
i delete all created files, because of no need to store all of them.
from openpyxl import load_workbook
import os
import app_config as config
import printers.printers as p
from datetime import datetime
import shutil
import time
class EditExcelTemplate:
def __init__(self, template_name):
now = datetime.now()
report_name = "_{}{}{}_{}{}{}_{}".format(now.year, now.month, now.day,
now.hour, now.minute, now.second,
now.microsecond)
self.report_path = config.EXCEL_REPORT_PATH.format(template_name +
report_name)
shutil.copy(src=config.EXCEL_TEMPLATE_PATH.format(template_name),
dst=self.report_path)
# self.wb = load_workbook(filename=config.EXCEL_TEMPLATE_PATH.format(template_name))
start_load = time.time()
self.wb = load_workbook(filename=self.report_path,
keep_links=False,
keep_vba=False,
data_only=True)
end_load = time.time()
print('LOAD WORKBOOK|{}'.format(str(end_load - start_load)))
self.ws = self.wb.active
self.answer = {'file_name': template_name.upper()}
def write_workbook(self, row_dest, column_dest, value):
c = self.ws.cell(row=row_dest, column=column_dest)
c.value = value
def save_excel(self):
self.wb.save(self.report_path)
def print_excel(self, printer_no):
p.print_excel(printer_no=printer_no, path_to_file=self.report_path)
def print_excel_file(self, printer_name):
p.print_excel_file(printer_name=printer_name, path_to_file=self.report_path)
import win32api
import app_config
import os, time
def print_excel(printer_no, path_to_file):
printer_name = app_config.PRINTER_NAMES[printer_no]
win32api.ShellExecute(
1,
'printto',
path_to_file,
'{}'.format(printer_name),
'.',
0
)
def delete_file(path_to_file, try_count=1):
if os.path.exists(path=path_to_file):
file_name = path_to_file.split('\\')[-1]
while try_count < 60:
try:
os.remove(path_to_file)
print('File {} deleted!'.format(file_name))
break
except PermissionError:
print('Can not delete file {}. Hold {} sec.'.format(file_name, try_count))
time.sleep(1.0)
try_count += 1

McAfee Update download script

I'm setting PC with McAfee install on them and be told that I need to stop the program going on line to download update (DAT). I need to create a script to download dat file from McAfee web site and put this file on server where McAfee can access and install this.
Has anyone done this in past.
I actually have done this. I haven't tested this script in a year or two but here is what I was using. This isn't written in Powershell but if you change the directories I think this can run on Windows.
#!/usr/bin/python
import ftplib
import tarfile
import shutil
import os
import re
import time
scannerDir = "/usr/local/uvscan/"
tmp = "/tmp/avscanner/"
def downloadDat():
datfile = ""
r = re.compile("^avvdat")
ftp = ftplib.FTP("ftp.nai.com", "anonymous", "email#yourdomain.com")
ftp.cwd("/pub/datfiles/english")
list = ftp.nlst()
for x in list:
if r.search(x):
datFile = x
f = open(tmp + "datfile", 'wb')
ftp.retrbinary("RETR " + datFile, f.write)
f.close()
ftp.quit()
def unpackDat():
tFile = tarfile.open(tmp + "datfile", 'r')
for f in tFile.getnames():
tFile.extract(f, tmp)
def createDirs():
if os.path.isdir(tmp) == False:
os.mkdir(tmp, 0700)
os.chown(tmp, 0, 95)
os.chmod(tmp, 0755)
def doCleanup():
shutil.rmtree(tmp)
def installFiles():
shutil.copyfile(tmp + "/avvclean.dat", scannerDir + "/avvclean.dat")
shutil.copyfile(tmp + "/avvnames.dat", scannerDir + "/avvnames.dat")
shutil.copyfile(tmp + "/avvscan.dat", scannerDir + "/avvscan.dat")
def isOld():
if os.path.isfile(scannerDir + "/avvclean.dat"):
if time.time() - os.path.getctime(scannerDir + "/avvclean.dat") < 80000:
return True
else:
return False
else:
return True
def main():
if isOld():
createDirs()
downloadDat()
unpackDat()
installFiles()
doCleanup()
if __name__ == "__main__":
main()