def saveProject(self):
"""
Save all variables to file
"""
prj_filename = self.showSaveDialog(self.tr('Save project to file'), "Project files (*%s)" % c.PROJECT_EXTENSION)
save_prj_filename = file_str(prj_filename[0])
# If Cancel was pressed
if not save_prj_filename:
return
(beg, ende) = os.path.split(save_prj_filename)
(fileBaseName, fileExtension) = os.path.splitext(ende)
if fileExtension != c.PROJECT_EXTENSION:
if not QtCore.QFile.exists(save_prj_filename):
save_prj_filename += c.PROJECT_EXTENSION
pyCode = self.d2g.export()
try:
# File open and write
f = open(save_prj_filename, "w")
f.write(str_encode(pyCode))
f.close()
logger.info(self.tr("Save project to FILE was successful"))
except IOError:
QMessageBox.warning(g.window,
self.tr("Warning during Save Project As"),
self.tr("Cannot Save the File"))
python类warning()的实例源码
def open_file(self, file_name=None):
if file_name:
try:
File(file_name, logging.root).open()
self.file = file_name
self.set_title(file_name)
self.add_recent_file(self.file)
self.init_model()
except Exception as e:
logging.exception(str(e))
self.delete_from_recent_files(file_name)
QMessageBox.warning(self, _('Error'), _('Cannot read file, format unknown') + ': ' + file_name)
def system_message(self, title, content, icon=None, msecs=5000):
if icon is None:
icon = 0
icon_val = {
'context': Qt.QSystemTrayIcon.Context,
'critical': Qt.QSystemTrayIcon.Critical,
'doubleclick': Qt.QSystemTrayIcon.DoubleClick,
'information': Qt.QSystemTrayIcon.Information,
'middleclick': Qt.QSystemTrayIcon.MiddleClick,
'noicon': Qt.QSystemTrayIcon.NoIcon,
'trigger': Qt.QSystemTrayIcon.Trigger,
'unknown': Qt.QSystemTrayIcon.Unknown,
'warning': Qt.QSystemTrayIcon.Warning
}
self.system_tray_icon.showMessage(title, content, icon_val[icon] if icon in icon_val else icon, msecs)
def split_printout(self, result):
try:
split_printout(result)
except NoResultToPrintException as e:
logging.warning(str(e))
mes = QMessageBox(self)
mes.setText(_('No results to print'))
mes.exec()
except NoPrinterSelectedException as e:
logging.warning(str(e))
mes = QMessageBox(self)
mes.setText(_('No printer selected'))
mes.exec()
def import_wo_wdb(self):
file_name = get_open_file_name(_('Open WDB Winorient file'), _("WDB Winorient (*.wdb)"))
if file_name is not '':
try:
winorient.import_wo_wdb(file_name)
except WDBImportError as e:
logging.exception(str(e))
QMessageBox.warning(self, _('Error'), _('Import error') + ': ' + file_name)
self.init_model()
def export_wo_wdb(self):
file_name = get_save_file_name(_('Save As WDB file'), _("WDB file (*.wdb)"),
'{}_sportorg_export'.format(time.strftime("%Y%m%d")))
if file_name is not '':
try:
wb = WinOrientBinary()
GlobalAccess().clear_filters(False)
wdb_object = wb.export()
GlobalAccess().apply_filters()
write_wdb(wdb_object, file_name)
except Exception as e:
logging.exception(str(e))
QMessageBox.warning(self, _('Error'), _('Export error') + ': ' + file_name)
def export_iof_result_list(self):
file_name = get_save_file_name(_('Save As IOF xml'), _("IOF xml (*.xml)"),
'{}_resultList'.format(time.strftime("%Y%m%d")))
if file_name is not '':
try:
iof_xml.export_result_list(file_name)
except Exception as e:
logging.exception(str(e))
QMessageBox.warning(self, _('Error'), _('Export error') + ': ' + file_name)
def parseText(argument, name):
if len(name) == len(argument):
QMessageBox.warning(None, "Arguments",
"No argument number found for %s. Remember to put name and "
"value adjacent! (e.g. -fps100)")
sys.exit(0)
return argument[len(name):]
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 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 autologoutwarn_accepted(self):
"""
Description: Callback issued when the user accepts the message box warning
about an imminent autologout event.
Arguments: None
Returns: Nothing
"""
self.lastclick = int(time())
self.autologoutWarn = False # This will make the warning be shown next times as well
def parseText(argument, name):
if len(name) == len(argument):
QMessageBox.warning(None, "Arguments",
"No argument number found for %s. Remember to put name and "
"value adjacent! (e.g. -fps100)")
sys.exit(0)
return argument[len(name):]
def onError(self, error):
if error == QSerialPort.ResourceError:
self.resourcesUnavailable.emit()
elif error == QSerialPort.PermissionError:
QMessageBox.warning(self.parent, \
"Warning", "Can not open %s\nIt may be already opened" % self.portName())
def showPopup(self):
self.clear()
self.updateList()
if self.lst == []:
QMessageBox.warning(self.parent, "Warning", "No device attached", QMessageBox.Ok, QMessageBox.NoButton)
super(ComboBox_Ports, self).showPopup()
def noMoleculesWarning(self):
QMessageBox.warning(self,'Failed to load predefined molecules',self.noMoleculesWarningMsg);
def no_user_list(self):
reply = message.warning(self, 'Warning', no_user_list_message, message.Ok)
return reply == message.Ok
def no_subreddit_list(self):
reply = message.warning(self, 'No Subreddit List', no_subreddit_list_message, message.Ok)
return reply == message.Ok
def remove_user_list(self):
reply = message.warning(self, 'Remove User List?', remove_user_list_message, message.Ok, message.Cancel)
return reply == message.Ok
def remove_subreddit_list(self):
reply = message.warning(self, 'Remove Subreddit List?', remove_subreddit_list_message, message.Ok, message.Cancel)
return reply == message.Ok
def downloader_running_warning(self):
text = 'The user finder is still currently running. Closing now may cause unexpected behaviour and corrupted ' \
'files. Are you sure you want to close?'
reply = message.warning(self, 'User Finder Still Running', text, message.Ok, message.Cancel)
return reply == message.Ok
def logout_warn(self):
"""
Description: Called if the warn_autologout setting has been set in the config. It
will warn user to reset their idle, otherwise an enforced logout will
be performed by calling the logout() method.
Arguments: None
Returns: Nothing
"""
self.autologoutwarnwin = QMessageBox(None)
self.autologoutwarnwin.setIcon(QMessageBox.Warning)
self.autologoutwarnwin.setText(_('auto_logout_warn'))
self.autologoutwarnwin.setWindowTitle(_('auto_logout_warn_title'))
self.autologoutwarnwin.setStandardButtons(QMessageBox.Ok)
self.autologoutwarnwin.buttonClicked.connect(self.autologoutwarn_accepted)
self.autologoutwarnwin.exec_()
def process_start(self, row, process, warn=True):
"""
Handle the startup of a B3 process.
:param row: the number of the row displaying the process state
:param process: the QProcess instance to start
:param warn: whether to warn the user of a startup failure or not
"""
if process.state() != QProcess.Running:
# refresh the config before running
process.config = process.config_path
self.paint_row(row)
if process.isFlag(CONFIG_READY):
process.stateChanged.connect(partial(self.paint_row, row=row))
process.start()
else:
if warn:
suffix = 'not found' if process.isFlag(CONFIG_FOUND) else 'not valid'
reason = 'configuration file %s: %s' % (suffix, process.config_path)
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('%s startup failure: %s' % (process.name, reason))
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
def __init__(self, problems, *args):
super(ProtocolWarningBox, self).__init__(*args)
self.setIcon(QMessageBox.Warning)
self.setWindowTitle("Insufficient protocol")
self.setText("The provided protocol is insufficient for this model.")
self.setInformativeText("The reported problems are: \n{}".format('\n'.join(' - ' + str(p) for p in problems)))
self._in_resize = False
def process_console(self, process):
"""
Display the STDOut console of a process.
"""
if not process.stdout:
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('%s console initialization failed!' % process.name)
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
else:
process.stdout.show()
def process_config(self, process):
"""
Open the B3 instance configuration file.
"""
if not process.isFlag(CONFIG_FOUND):
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('Missing %s configuration file' % process.name)
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
else:
B3App.Instance().openpath(process.config.fileName)
def process_log(self, process):
"""
Open the B3 instance log file.
"""
try:
if not process.isFlag(CONFIG_FOUND):
raise ConfigFileNotFound('missing configuration file (%s)' % process.config_path)
elif not process.isFlag(CONFIG_VALID):
raise ConfigFileNotValid('invalid configuration file (%s)' % process.config_path)
if not process.config.has_option('b3', 'logfile'):
raise Exception('missing b3::logfile option in %s configuration file' % process.name)
path = b3.getAbsolutePath(process.config.get('b3', 'logfile'), decode=True, conf=process.config)
if not os.path.isfile(path):
message = '- missing: %s' % path
path = os.path.join(b3.HOMEDIR, os.path.basename(path))
if not os.path.isfile(path):
raise Exception(message + '\n- missing: %s' % path)
except Exception, err:
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('%s log file no found' % process.name)
msgbox.setDetailedText(err.message)
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.layout().addItem(QSpacerItem(400, 0, QSizePolicy.Minimum, QSizePolicy.Expanding),
msgbox.layout().rowCount(), 0, 1, msgbox.layout().columnCount())
msgbox.exec_()
else:
B3App.Instance().openpath(path)
def open_extplugins_directory(self):
"""
Open the default extplugins directory.
"""
self.make_visible()
extplugins_dir = b3.getAbsolutePath('@b3/extplugins', True)
if not os.path.isdir(extplugins_dir):
try:
LOG.warning('missing %s directory: attempt to create it' % extplugins_dir)
os.mkdir(extplugins_dir)
with open(os.path.join(extplugins_dir, '__init.__py'), 'w') as f:
f.write('#')
except Exception, err:
LOG.error('could create default extplugins directory: %s', err)
msgbox = QMessageBox()
msgbox.setIcon(QMessageBox.Warning)
msgbox.setWindowTitle('WARNING')
msgbox.setText('Missing 3rd party plugins directory!')
msgbox.setDetailedText('B3 could not create missing 3rd party plugins directory (%s). '
'Please make sure B3 has writing permissions on "%s"' % (extplugins_dir,
b3.getAbsolutePath('@b3//', True)))
msgbox.setStandardButtons(QMessageBox.Ok)
msgbox.exec_()
return
else:
LOG.debug('created directory %s: resuming directory prompt' % extplugins_dir)
B3App.Instance().openpath(extplugins_dir)
def deleteFile(self, menu):
# show Warning message to the user.
# check persepolis_setting first!
# perhaps user checked "do not show this message again"
delete_warning_message = self.persepolis_setting.value(
'MainWindow/delete-warning', 'yes')
if delete_warning_message == 'yes':
self.msgBox = QMessageBox()
self.msgBox.setText("<b><center>This operation will delete \
downloaded files from your hard disk<br>PERMANENTLY!</center></b>")
self.msgBox.setInformativeText("<center>Do you want to continue?</center>")
self.msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
self.msgBox.setIcon(QMessageBox.Warning)
dont_show_checkBox = QtWidgets.QCheckBox("don't show this message again")
self.msgBox.setCheckBox(dont_show_checkBox)
reply = self.msgBox.exec_()
# if user checks "do not show this message again!", change persepolis_setting!
if self.msgBox.checkBox().isChecked():
self.persepolis_setting.setValue(
'MainWindow/delete-warning', 'no')
# do nothing if user clicks NO
if reply != QMessageBox.Yes:
return
# if checking_flag is equal to 1, it means that user pressed remove or
# delete button or ... . so checking download information must be
# stopped until job is done!
if checking_flag != 2:
wait_check = WaitThread()
self.threadPool.append(wait_check)
self.threadPool[len(self.threadPool) - 1].start()
self.threadPool[len(self.threadPool) -
1].QTABLEREADY.connect(self.deleteFile2)
else:
self.deleteFile2()
def deleteSelected(self, menu):
# showing Warning message to the user.
# checking persepolis_setting first!
# perhaps user was checking "do not show this message again"
delete_warning_message = self.persepolis_setting.value(
'MainWindow/delete-warning', 'yes')
if delete_warning_message == 'yes':
self.msgBox = QMessageBox()
self.msgBox.setText("<b><center>This operation will delete \
downloaded files from your hard disk<br>PERMANENTLY!</center></b>")
self.msgBox.setInformativeText("<center>Do you want to continue?</center>")
self.msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
self.msgBox.setIcon(QMessageBox.Warning)
dont_show_checkBox = QtWidgets.QCheckBox("don't show this message again")
self.msgBox.setCheckBox(dont_show_checkBox)
reply = self.msgBox.exec_()
# if user checks "do not show this message again!", change persepolis_setting!
if self.msgBox.checkBox().isChecked():
self.persepolis_setting.setValue(
'MainWindow/delete-warning', 'no')
# do nothing if user clicks NO
if reply != QMessageBox.Yes:
return
# if checking_flag is equal to 1, it means that user pressed remove or
# delete button or ... . so checking download information must be
# stopped until job is done!
if checking_flag != 2:
wait_check = WaitThread()
self.threadPool.append(wait_check)
self.threadPool[len(self.threadPool) - 1].start()
self.threadPool[len(self.threadPool) -
1].QTABLEREADY.connect(self.deleteSelected2)
else:
self.deleteSelected2()
def removeQueue(self, menu):
# show Warning message to user.
# checks persepolis_setting first!
# perhaps user was checking "do not show this message again"
remove_warning_message = self.persepolis_setting.value(
'MainWindow/remove-queue-warning', 'yes')
if remove_warning_message == 'yes':
self.remove_queue_msgBox = QMessageBox()
self.remove_queue_msgBox.setText('<b><center>This operation will remove \
all download items in this queue<br>from "All Downloads" list!</center></b>')
self.remove_queue_msgBox.setInformativeText("<center>Do you want to continue?</center>")
self.remove_queue_msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
self.remove_queue_msgBox.setIcon(QMessageBox.Warning)
dont_show_checkBox = QtWidgets.QCheckBox("don't show this message again")
self.remove_queue_msgBox.setCheckBox(dont_show_checkBox)
reply = self.remove_queue_msgBox.exec_()
# if user checks "do not show this message again!", change persepolis_setting!
if self.remove_queue_msgBox.checkBox().isChecked():
self.persepolis_setting.setValue(
'MainWindow/remove-queue-warning', 'no')
# do nothing if user clicks NO
if reply != QMessageBox.Yes:
return
# find name of queue
current_category_tree_text = str(current_category_tree_index.data())
if current_category_tree_text == 'Scheduled Downloads':
error_messageBox = QMessageBox()
error_messageBox.setText(
"<b>Sorry! You can't remove default queue!</b>")
error_messageBox.setWindowTitle('Error!')
error_messageBox.exec_()
return
if current_category_tree_text != 'All Downloads' and current_category_tree_text != 'Single Downloads':
# remove queue from category_tree
row_number = current_category_tree_index.row()
self.category_tree_model.removeRow(row_number)
# delete category from data base
self.persepolis_db.deleteCategory(current_category_tree_text)
# highlight "All Downloads" in category_tree
all_download_index = self.category_tree_model.index(0, 0)
self.category_tree.setCurrentIndex(all_download_index)
self.categoryTreeSelected(all_download_index)
# this method starts the queue that is selected in category_tree