def fatal(message):
if QMessageBox:
try:
app = QApplication(sys.argv)
QMessageBox.critical(None, 'Error', str(message))
except BaseException as exc:
print('fatal:', message)
print('during handling of the above error, following error occured')
print('fatal:', exc)
else:
print('fatal:', message)
sys.exit(1)
python类critical()的实例源码
def fatal(message):
if QMessageBox:
try:
app = QApplication(sys.argv)
QMessageBox.critical(None, 'Error', str(message))
except BaseException as exc:
print('fatal:', message)
print('during handling of the above error, following error occured')
print('fatal:', exc)
else:
print('fatal:', message)
sys.exit(1)
def launchError(self, error):
if error != QProcess.Crashed:
QMessageBox.critical(None, "Failed to launch the example",
"Could not launch the example. Ensure that it has been "
"built.",
QMessageBox.Cancel)
def change_status(self, rowid):
"""
Description: If the user clicks on the column which determines VM's status, we'll allow them
to change VM's status. This method shows a confirmation dialog and if accepted,
it will be notified to oVirt.
Arguments: The row id that has been clicked. This relationship is stored using the VmData class.
Returns: Nothing
"""
global conf
self.lastclick = int(time()) # Last click timestamp update
curvmstatus = self.vmdata[rowid].vmstatus
if curvmstatus != 'up' and curvmstatus != 'down':
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status'))
return
reply = QMessageBox.question(None, _('apptitle') + ': ' + _('confirm'), '%s <b>%s</b>. %s: <b>%s</b>.' % (_('current_vm_status'), self.current_vm_status(curvmstatus), _('confirm_vm_status_change'), self.toggle_vm_action(curvmstatus)), QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
try:
vm = conf.OVIRTCONN.vms.get(id=self.vmdata[rowid].vmid)
except ConnectionError:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_connection_drop'))
quit()
if curvmstatus == 'up':
try:
vm.shutdown()
QMessageBox.information(None, _('apptitle') + ': ' + _('success'), _('shutting_down_vm'))
except RequestError:
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status'))
if curvmstatus == 'down':
try:
vm.start()
QMessageBox.information(None, _('apptitle') + ': ' + _('success'), _('powering_up_vm'))
except RequestError:
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('vm_in_unchangeable_status'))
def store_vv_file(self, vmid, ticket):
"""
Description: Connecting to the machine involves two steps, the second one is obtaining a 'vv' file with the
connection parameters, which we can later pipe to virt-viewer and the connection will be opened.
Arguments: 1. vmid: The VM UUID in oVirt-format.
2. ticket: The ticket obtained in the first step (method get_viewer_ticket)
Returns: The temporary filename with all the parameters to connect to the machine (piped to virt-viewer)
"""
global conf
if not ticket:
return False
req = urllib2.Request('%s/%s/%s/%s/%s' % (conf.CONFIG['ovirturl'], 'vms', vmid, 'graphicsconsoles', ticket))
base64str = encodestring('%s:%s' % (conf.USERNAME + '@' + conf.CONFIG['ovirtdomain'], conf.PASSWORD)).replace('\n', '')
req.add_header('Authorization', 'Basic ' + base64str)
req.add_header('Content-Type', 'application/xml')
req.add_header('Accept', 'application/x-virt-viewer')
req.add_header('filter', 'true')
unverified_ctxt = SSLContext(PROTOCOL_TLSv1)
try:
contents = urllib2.urlopen(req, context=unverified_ctxt).read()
if conf.CONFIG['fullscreen'] == '1':
contents = contents.replace('fullscreen=0', 'fullscreen=1')
filename = '/tmp/viewer-' + str(randint(10000, 99999))
f = open(filename, 'w')
f.write(contents)
f.close()
return filename
except urllib2.HTTPError, em:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_request_error') + '(' + str(em.code) + '): ' + em.reason + '. ' + _('check_vm_config_updated'))
return None
def connect(self, rowid):
"""
Description: Whenever the user clicks on the 'connect' row, this method will make
sure the VM status is up and only then will call the connect2machine method.
Arguments: The row id that has been clicked. This relationship is stored using the VmData class.
Returns: Nothing
"""
self.lastclick = int(time()) # Last click timestamp update
vmid = self.vmdata[rowid].vmid
vmname = self.vmdata[rowid].vmname
vmstatus = self.vmdata[rowid].vmstatus
if vmstatus != 'up':
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('cannot_connect_if_vm_not_up'))
return
if vmname in self.openviewer_vms:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('cannot_open_more_viewer_sessions'))
return
self.openviewer_vms.append(vmname)
self.refresh_grid() # Enforce a dashboard reload to make the icon refresh
self.connect2machine(vmid, vmname)
def launchError(self, error):
if error != QProcess.Crashed:
QMessageBox.critical(None, "Failed to launch the example",
"Could not launch the example. Ensure that it has been "
"built.",
QMessageBox.Cancel)
def validation_error(self,message):
if (self.hardcore):
QMessageBox.critical(self,'Validation error',"Moron!");
else:
QMessageBox.critical(self,'Validation error',message);
raise ValueError(message);
def calcDone(self):
self.enable_Go_button();
if (self.calc.error):
QMessageBox.critical(self,'Calculation error',str(self.calc.error));
else:
self.last_result = self.calc.result;
self.enable_save_option();
self.present_results();
def on_btn_start_clicked(self):
if self.ui.actionStart.text() == u'Start':
try:
self.jlink = jlink.Jlink(jlinkdllpath)
self.jlink.get_hardware_verion()
self.jlink.set_mode(jlink.JLINK_MODE_SWD)
self.jlink.set_speed(4000)
self.RTT_addr = self.get_RTT_addr()
self.setup_ring_buffer()
self.ui.statusbar.showMessage(u"??????")
self.ui.actionStart.setText(u'Stop')
except jlink.JlinkError as e:
QMessageBox.critical(self, u"??", u"'{}'.".format(e))
#self.on_btn_dll_clicked()
del self.jlink
self.jlink = None
except Exception as e:
print(e)
self.ui.statusbar.showMessage(u"??????")
else:
self.ui.actionStart.setText(u'Start')
time.sleep(0.1)
self.jlink.close()
del self.jlink
self.jlink = None
self.ui.statusbar.showMessage(u"??????")
def on_received(self, bytesUp):
try:
self.ui.plainTextEdit.moveCursor(QtGui.QTextCursor.End)
self.ui.plainTextEdit.insertPlainText(bytesUp.decode())
self.ui.plainTextEdit.moveCursor(QtGui.QTextCursor.End)
self.lineLbl.setText(str(self.ui.plainTextEdit.document().lineCount()))
except Exception as e:
QMessageBox.critical(self, u"??", str(e))
Unhandled_Python_ Exceptions_02_alternative.py 文件源码
项目:OpenTutorials_PyQt
作者: RavenKyu
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def exception_hook(t, val, tb):
QMessageBox.critical(None, "An exception was raised", "Exception type: {}".format(t))
old_exception_hook(t, val, tb)
def mine(self):
d=self.path.text()
name=self.exeline.text()
if d!='Path to the file used to start miner' and d!='':
if os.path.isfile(d)==True:
d='/'.join(d.split('/')[:-1])
try:
os.chdir(d)
process.start(name)
self.tnow=time.time()
except PermissionError:
QMessageBox.critical(self,"Error","Problems when accessing directory",QMessageBox.Ok)
except FileNotFoundError:
QMessageBox.critical(self,"Error","Bad directory path",QMessageBox.Ok)
def save_data_dialog(signal_name: str, data, wav_only=False, parent=None) -> str:
filename = get_save_file_name(signal_name, wav_only)
if filename:
try:
save_data(data, filename)
except Exception as e:
QMessageBox.critical(parent, "Error saving signal", e.args[0])
filename = None
else:
filename = None
return filename
def generic_error(title: str, msg: str, detailed_msg: str = None):
w = QWidget()
if detailed_msg:
msg = "Error: <b>" + msg.replace("\n",
"<br>") + "</b>" + "<br><br>----------<br><br>" + detailed_msg.replace(
"\n", "<br>")
QMessageBox.critical(w, title, msg)
def no_device():
w = QWidget()
QMessageBox.critical(w, w.tr("No devices"),
w.tr("You have to choose at least one available "
"device in Edit->Options->Device."))
def empty_selection():
w = QWidget()
QMessageBox.critical(w, w.tr("No selection"),
w.tr("Your selection is empty!"))
def usrp_found():
w = QWidget()
QMessageBox.critical(w, w.tr("USRP not found"),
w.tr("USRP could not be found . Is the IP "
"correct?"))
def gnuradio_not_installed():
w = QWidget()
QMessageBox.critical(w, w.tr("Gnuradio not found"),
w.tr("You need to install Gnuradio for this "
"feature."))
def empty_group():
w = QWidget()
QMessageBox.critical(w, w.tr("Empty group"),
w.tr("The group may not be empty."))
def exception_message(log_lines, exc_info):
stacktrace = traceback.format_exception(*exc_info) if exc_info else ""
message = """
{log_lines}
----
{stacktrace}
""".format(log_lines='\n'.join(log_lines), stacktrace='\n'.join(stacktrace))
mb = QMessageBox()
mb.setIcon(QMessageBox.Critical)
mb.setWindowTitle("DUANG!!!")
mb.setText('A critical error occurred. Select the details to display it.')
mb.setInformativeText("Please report it to "
"<a href=https://github.com/bioinformatist/Gao-s-SB/issues/new>the owner's GitHub</a>")
mb.setTextFormat(Qt.RichText)
mb.setDetailedText(message)
mb.setTextInteractionFlags(Qt.TextSelectableByMouse)
mb.exec()
def _export_image(self):
output_file = self.outputFile_box.text()
if not any(output_file.endswith(el[0]) for el in self._extension_filters):
output_file += '.{}'.format(self._extension_filters[0][0])
try:
self._plotting_frame.export_image(output_file, self.width_box.value(), self.height_box.value(),
dpi=self.dpi_box.value())
self.previous_values['width'] = self.width_box.value()
self.previous_values['height'] = self.height_box.value()
self.previous_values['dpi'] = self.dpi_box.value()
self.previous_values['output_file'] = self.outputFile_box.text()
self.previous_values['writeScriptsAndConfig'] = self.writeScriptsAndConfig.isChecked()
if self.writeScriptsAndConfig.isChecked():
output_basename = os.path.splitext(output_file)[0]
self._write_config_file(output_basename + '.conf')
self._write_python_script_file(output_basename + '_script.py', output_basename + '.conf', output_file,
self.width_box.value(), self.height_box.value(), self.dpi_box.value())
self._write_bash_script_file(output_basename + '_script.sh', output_basename + '.conf', output_file,
self.width_box.value(), self.height_box.value(), self.dpi_box.value())
except PermissionError as error:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Could not write the file to the given destination.")
msg.setInformativeText(str(error))
msg.setWindowTitle("Permission denied")
msg.exec_()
def _write_example_data(self):
try:
mdt.utils.get_example_data(self.outputFile.text())
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText('The MDT example data has been written to {}.'.format(self.outputFile.text()))
msg.setWindowTitle('Success')
msg.exec_()
except IOError as e:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText(str(e))
msg.setWindowTitle("File writing error")
msg.exec_()
def displayMessageBox(self, errors_list):
"""
Popup a message box in order to display an error message
@param errors_list: a string that contains all the errors
"""
errors_list = self.tr('Please correct the following error(s):\n') + errors_list
error_message = QMessageBox(QMessageBox.Critical, self.tr('Invalid changes'), errors_list);
error_message.exec_()
def error_dlg(parent,text):
msgBox = QMessageBox(parent)
msgBox.setIcon(QMessageBox.Critical)
msgBox.setText("gpvdm error:")
msgBox.setInformativeText(text)
msgBox.setStandardButtons(QMessageBox.Ok )
msgBox.setDefaultButton(QMessageBox.Ok)
reply = msgBox.exec_()
def run_gui():
"""
Run B3 graphical user interface.
Will raise an exception if the GUI cannot be initialized.
"""
from b3.gui import B3App
from b3.gui.misc import SplashScreen
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QSpacerItem, QSizePolicy
# initialize outside try/except so if PyQt5 is not avaiable or there is
# no display adapter available, this will raise an exception and we can
# fallback into console mode
app = B3App.Instance(sys.argv)
try:
with SplashScreen(min_splash_time=2):
mainwindow = app.init()
except Exception, e:
box = QMessageBox()
box.setIcon(QMessageBox.Critical)
box.setWindowTitle('CRITICAL')
box.setText('CRITICAL: B3 FAILED TO START!')
box.setInformativeText('ERROR: %s' % e)
box.setDetailedText(traceback.format_exc())
box.setStandardButtons(QMessageBox.Ok)
# this will trick Qt and resize a bit the QMessageBox to the exception stack trace is printed nice
box.layout().addItem(QSpacerItem(400, 0, QSizePolicy.Minimum, QSizePolicy.Expanding),
box.layout().rowCount(), 0, 1, box.layout().columnCount())
box.exec_()
sys.exit(127)
else:
mainwindow.make_visible()
sys.exit(app.exec_())
def make_new_process(self, path):
"""
Create a new B3 process using the provided configuration file path.
NOTE: this actually handle also the repainting of the main table but
since it's not a toolbar button handler it has been implemented here instead.
:param path: the configuration file path
"""
if path:
try:
abspath = b3.getAbsolutePath(path)
config = MainConfig(load_config(abspath))
except ConfigFileNotValid:
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Critical)
msgbox.setWindowTitle('WARNING')
msgbox.setText('You selected an invalid configuration file')
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
else:
analysis = config.analyze()
if analysis:
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Critical)
msgbox.setWindowTitle('ERROR')
msgbox.setText('One or more problems have been detected in your configuration file')
msgbox.setDetailedText('\n'.join(analysis))
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
else:
if not B3.exists(config.fileName):
process = B3(config=config)
process.insert()
main_table = self.centralWidget().main_table
main_table.repaint()
def __init_storage(self):
"""
Initialize the connection with the SQLite database.
:raise DatabaseError: if the database schema is not consistent.
"""
is_new_database = not os.path.isfile(B3_STORAGE)
self.storage = sqlite3.connect(B3_STORAGE, check_same_thread=False)
self.storage.isolation_level = None # set autocommit mode
self.storage.row_factory = sqlite3.Row # allow row index by name
if is_new_database:
# create new schema
self.__build_schema()
else:
# check database schema
LOG.debug('checking database schema')
cursor = self.storage.cursor()
cursor.execute("""SELECT * FROM sqlite_master WHERE type='table'""")
tables = [row[1] for row in cursor.fetchall()]
cursor.close()
if 'b3' not in tables:
LOG.debug('database schema is corrupted: asking the user if he wants to rebuild it')
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Critical)
msgbox.setText('The database schema is corrupted and must be rebuilt. Do you want to proceed?')
msgbox.setInformativeText('NOTE: all the previously saved data will be lost!')
msgbox.setStandardButtons(QMessageBox.No | QMessageBox.Yes)
msgbox.setDefaultButton(QMessageBox.No)
msgbox.exec_()
if msgbox.result() == QMessageBox.No:
# critical will raise an exception which will terminate the QApplication
LOG.critical('could not start B3: database schema is corrupted!')
try:
os.remove(B3_STORAGE)
self.__build_schema()
except Exception, err:
raise LOG.critical('could initialize SQLite database: %s (%s): make sure B3 has permissions to '
'operate on this file, or remove it manually', B3_STORAGE, err)
def excepthook(excType, excValue, tracebackobj):
"""Rewritten "excepthook" function, to display a message box with details about the exception.
@param excType exception type
@param excValue exception value
@param tracebackobj traceback object
"""
separator = '-' * 40
notice = "An unhandled exception has occurred\n"
tbinfofile = io.StringIO()
traceback.print_tb(tracebackobj, None, tbinfofile)
tbinfofile.seek(0)
tbinfo = tbinfofile.read()
errmsg = '%s: \n%s' % (str(excType), str(excValue))
sections = [separator, errmsg, separator, tbinfo]
msg = '\n'.join(sections)
# Create a QMessagebox
error_box = QMessageBox()
error_box.setText(str(notice)+str(msg))
error_box.setWindowTitle("Hue-plus - unhandled exception")
error_box.setIcon(QMessageBox.Critical)
error_box.setStandardButtons(QMessageBox.Ok)
error_box.setTextInteractionFlags(Qt.TextSelectableByMouse)
# Show the window
error_box.exec_()
sys.exit(1)