def __init__(self, link_url: str, dl_path: str, parent=None):
super(Downloader, self).__init__(parent)
self.parent = parent
self.dltool_cmd = find_executable(self.download_cmd)
self.download_link = link_url
self.download_path = dl_path
if self.dltool_cmd.strip():
self.dltool_args = self.dltool_args.format(dl_path=self.download_path, dl_link=self.download_link)
self.console = QTextEdit(self.parent)
self.console.setWindowTitle('%s Downloader' % qApp.applicationName())
self.proc = QProcess(self.parent)
layout = QVBoxLayout()
layout.addWidget(self.console)
self.setLayout(layout)
self.setFixedSize(QSize(400, 300))
else:
QMessageBox.critical(self.parent, 'DOWNLOADER ERROR', '<p>The <b>aria2c</b> executable binary could not ' +
'be found in your installation folders. The binary comes packaged with this ' +
'application so it is likely that it was accidentally deleted via human ' +
'intervntion or incorrect file permissions are preventing access to it.</p>' +
'<p>You may either download and install <b>aria2</b> manually yourself, ensuring ' +
'its installation location is globally accessible via PATH environmnt variables or ' +
'simply reinstall this application again. If the issue is not resolved then try ' +
'to download the application again incase the orignal you installed already was ' +
'corrupted/broken.', buttons=QMessageBox.Close)
python类critical()的实例源码
def trainSystem(self):
"""
Orders the AppController to train a model based on the selected database.
Parameters
----------
None
Return
----------
None
"""
if self.path_train:
trained = self.controller.train(self.path_train, self.comboBoxDatabaseTrain.currentText())
self.path_train = None
if not trained:
QMessageBox.critical(self.train, "Message", "File columns or labels mismatch.")
else:
QMessageBox.information(self.train, "Message", "Training succesful.")
else:
QMessageBox.warning(self.train, "Message", "Must pick a database file.")
def _start(self, flash, erase):
self._flash_output = bytearray()
self.outputEdit.setPlainText("")
python_path = self.pythonPathEdit.text()
if not python_path:
QMessageBox.critical(self, "Error", "Python2 path was not set.")
return
firmware_file = None
if flash:
firmware_file = self.firmwarePathEdit.text()
if not firmware_file:
QMessageBox.critical(self, "Error", "Firmware file was not set.")
return
self._port = self._connection_scanner.port_list[self.portComboBox.currentIndex()]
job_thread = Thread(target=self._flash_job, args=[python_path, firmware_file, erase])
job_thread.setDaemon(True)
job_thread.start()
self.eraseButton.setEnabled(False)
self.flashButton.setEnabled(False)
self._flashing = True
def scrape(self, pagenum: int) -> None:
try:
url = self.source_url.format(pagenum + 1)
req = requests.get(url, headers={'User-Agent': self.user_agent}, proxies=self.proxy)
bs = BeautifulSoup(req.text, 'lxml')
posts = bs('div', class_='post')
for post in posts:
dlsize = post.find('h2').get_text().strip()
table_row = [
post.find('div', class_='p-c p-c-time').get_text().strip(),
post.find('a', class_='p-title').get('href').strip(),
post.find('a', class_='p-title').get_text().strip(),
dlsize[dlsize.rfind('(') + 1:len(dlsize) - 1]
]
self.addRow.emit(table_row)
except HTTPError:
sys.stderr.write(sys.exc_info()[0])
QMessageBox.critical(self, 'ERROR NOTIFICATION', sys.exc_info()[0])
# self.exit()
def connect(self, endpoint: str, payload: object=None) -> object:
try:
headers = {
'Authorization': 'Bearer %s' % self.api_token,
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
}
res = requests.post('%s%s' % (self.api_url, endpoint), headers=headers, data=payload,
proxies=self.proxy, verify=False)
return res.json()
except HTTPError:
print(sys.exc_info())
QMessageBox.critical(self, 'ERROR NOTIFICATION',
'<h3>Real-Debrid API Error</h3>' +
'A problem occurred whilst communicating with Real-Debrid. Please check your '
'Internet connection.<br/><br/>' +
'<b>ERROR LOG:</b><br/>(Error Code %s) %s<br/>%s'
% (qApp.applicationName(), HTTPError.code, HTTPError.reason), QMessageBox.Ok)
# self.exit()
def setup_runtime(uconfig):
from bot.duel_links_runtime import DuelLinkRunTime
from bot import logger
from bot.providers import get_provider
os.makedirs(uconfig.get('locations', 'log'), exist_ok=True)
setup_logging()
scheduler = BackgroundScheduler()
dlRuntime = DuelLinkRunTime(uconfig, scheduler)
dlRuntime.stop = False # Need to Ensure that it runs
scheduler.start()
try:
dlRuntime.set_provider(get_provider(uconfig.get('bot', 'provider'))(scheduler, uconfig, dlRuntime))
except Exception as e:
logger.critical("Could not get a provider, take a look at your config file")
logger.critical(e)
sys.exit(1)
try:
dlRuntime.get_provider().sleep_factor = uconfig.getint('bot', 'sleep_factor')
except Exception as e:
logger.critical("Could not set sleep factor, take a look at your config file")
logger.critical(e)
sys.exit(1)
return dlRuntime
def gui(start, config_file):
if start:
import sys
from PyQt5.QtWidgets import QSystemTrayIcon
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QApplication
from bot.utils.common import make_config_file, default_config
from bot.duel_links_runtime import DuelLinkRunTime
from bot.dl_gui import DuelLinksGui
app = QApplication(sys.argv)
if not QSystemTrayIcon.isSystemTrayAvailable():
QMessageBox.critical(None, "Systray",
"Systray not dected on system.")
sys.exit(1)
QApplication.setQuitOnLastWindowClosed(False)
uconfig = default_config()
uconfig.read(config_file)
dlRuntime = setup_runtime(uconfig)
dlRuntime.main()
window = DuelLinksGui(dlRuntime)
window.show()
sys.exit(app.exec_())
def __init__(self, parent=None):
super(VideoService, self).__init__(parent)
self.parent = parent
self.logger = logging.getLogger(__name__)
try:
self.backends = VideoService.findBackends()
self.proc = VideoService.initProc()
if hasattr(self.proc, 'errorOccurred'):
self.proc.errorOccurred.connect(self.cmdError)
self.lastError = ''
self.media, self.source = None, None
self.keyframes = []
self.streams = Munch()
except FFmpegNotFoundException as e:
self.logger.exception(e.msg, exc_info=True)
QMessageBox.critical(getattr(self, 'parent', None), 'Missing libraries', e.msg, QMessageBox.Ok)
def showDocInAssistant(self, name):
url = self.resolveDocUrl(name)
Colors.debug("Sending URL to Assistant:", url)
# Start assistant if it's not already running.
if self.assistantProcess.state() != QProcess.Running:
app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator()
if sys.platform == 'darwin':
app += 'Assistant.app/Contents/MacOS/Assistant'
else:
app += 'assistant'
args = ['-enableRemoteControl']
self.assistantProcess.start(app, args)
if not self.assistantProcess.waitForStarted():
QMessageBox.critical(None, "PyQt Demo",
"Could not start %s." % app)
return
# Send command through remote control even if the process was just
# started to activate assistant and bring it to the front.
cmd_str = QTextStream(self.assistantProcess)
cmd_str << 'SetSource ' << url << '\n'
def connect2machine(self, vmid, vmname):
"""
Description: Connecting to the machine involves two steps, this method does both and
makes sure everything is ok to call virt-viewer afterwards.
Arguments: 1. vmid: The VM UUID in oVirt-format.
2. vmname: Just for displaying purposes, the VM name
Returns: Nothing. Opens the view-viewer display.
"""
viewer_ticket = self.get_viewer_ticket(vmid)
filename = self.store_vv_file(vmid, viewer_ticket)
if filename:
self.create_viewer_thread(vmname, filename)
else:
if vmname in self.openviewer_vms:
self.openviewer_vms.remove(vmname) # Remove the VM from the list of opened viewers
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('no_viewer_file'))
def acquire_vm_from_vmpool(self, rowid):
"""
Description: A machine will be acquired by a user if they click on the icon of a VmPool
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
vmtype = self.vmdata[rowid].vmtype
if vmtype == 'vmpool':
try:
QMessageBox.information(None, _('apptitle') + ': ' + _('info'), _('acquiring_vm_from_pool'))
vmp = conf.OVIRTCONN.vmpools.get(id=self.vmdata[rowid].vmid)
vmp.allocatevm()
self.refresh_grid()
except ConnectionError:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('unexpected_connection_drop'))
quit()
except RequestError:
QMessageBox.critical(None, _('apptitle') + ': ' + _('error'), _('cannot_attach_vm_to_user'))
else:
QMessageBox.warning(None, _('apptitle') + ': ' + _('warning'), _('object_is_not_a_vmpool'))
def __init__(self):
self.anki = AnkiBridge()
self.server = AjaxServer(self.handler)
try:
self.server.listen()
self.timer = QTimer()
self.timer.timeout.connect(self.advance)
self.timer.start(TICK_INTERVAL)
except:
QMessageBox.critical(
self.anki.window(),
'AnkiConnect',
'Failed to listen on port {}.\nMake sure it is available and is not in use.'.format(NET_PORT)
)
def upgrade(self):
response = QMessageBox.question(
self.anki.window(),
'AnkiConnect',
'Upgrade to the latest version?',
QMessageBox.Yes | QMessageBox.No
)
if response == QMessageBox.Yes:
data = download(URL_UPGRADE)
if data is None:
QMessageBox.critical(self.anki.window(), 'AnkiConnect', 'Failed to download latest version.')
else:
path = os.path.splitext(__file__)[0] + '.py'
with open(path, 'w') as fp:
fp.write(makeStr(data))
QMessageBox.information(self.anki.window(), 'AnkiConnect', 'Upgraded to the latest version, please restart Anki.')
return True
return False
def showDocInAssistant(self, name):
url = self.resolveDocUrl(name)
Colors.debug("Sending URL to Assistant:", url)
# Start assistant if it's not already running.
if self.assistantProcess.state() != QProcess.Running:
app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator()
if sys.platform == 'darwin':
app += 'Assistant.app/Contents/MacOS/Assistant'
else:
app += 'assistant'
args = ['-enableRemoteControl']
self.assistantProcess.start(app, args)
if not self.assistantProcess.waitForStarted():
QMessageBox.critical(None, "PyQt Demo",
"Could not start %s." % app)
return
# Send command through remote control even if the process was just
# started to activate assistant and bring it to the front.
cmd_str = QTextStream(self.assistantProcess)
cmd_str << 'SetSource ' << url << '\n'
def calculate(self):
inputs = self.validate_input();
if (inputs is not False):
Jmax,Kmax,Mmax = inputs;
self.setEnabled(False);
self.update();
QMessageBox.information(self,'Responsiveness','This user interface will be irresponsive while the calculation is carried out.\n\nSorry about that!');
try:
U2dcalc.set_num_threads(multiprocessing.cpu_count());
U2dcalc.precalculate_matrix_elements(Jmax,Kmax,Mmax);
self.update_available();
QMessageBox.information(self,'Success!','Calculation done.');
self.close();
except BaseException as e:
QMessageBox.critical(self,'Failed to calculate matrix elements',str(e));
self.setEnabled(True);
else:
QMessageBox.critical(self,'Validation error',"Invalid input");
def delete_group(self, group_item: ProtocolTreeItem):
if self.rootItem.childCount() == 1:
QMessageBox.critical(self.controller, self.tr("Group not deletable"),
self.tr(
"You can't delete the last group. Think about the children, they would be homeless!"))
return
group_id = self.rootItem.index_of(group_item)
if group_id == 0:
new_group_index = 1
else:
new_group_index = group_id - 1
new_group = self.rootItem.children[new_group_index]
for i in reversed(range(group_item.childCount())):
new_group.appendChild(group_item.children[i])
self.removeRow(group_id, QModelIndex())
self.group_deleted.emit(group_id, new_group_index)
def hackrf_not_found():
w = QWidget()
if sys.platform == "win32":
msg = "Could not connect to HackRF. Try these solutions:" \
"<br/><br/> 1. Ensure HackRF is plugged in." \
"<br/> 2. <b>Install HackRF USB driver</b> with <a href='http://zadig.akeo.ie/'>Zadig</a>."
else:
msg = "Could not connect to HackRF. Try these solutions:" \
"<br/><br/> 1. Ensure HackRF is plugged in." \
"<br/> 2. Run the command <b>hackrf_info</b> in terminal as root." \
"<br/> 3. If 2. works for you, follow the instructions " \
"<a href='https://github.com/mossmann/hackrf/wiki/FAQ'>here</a>."
QMessageBox.critical(w, w.tr("HackRF not found"),
w.tr(msg))
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol: ProtocolAnalyzer, view: int):
"""
:type parent: QTableView
:type undo_stack: QUndoStack
:type protocol_analyzers: list of ProtocolAnalyzer
"""
min_row, max_row, start, end = sel_range
if min_row == -1 or max_row == -1 or start == -1 or end == -1:
return None
if max_row != min_row:
QMessageBox.critical(parent, self.tr("Error in MessageBreak"),
self.tr("You can only break one line per action."))
return None
end = protocol.convert_index(end, view, 0, True, message_indx=min_row)[0]
# factor = 1 if view == 0 else 4 if view == 1 else 8
self.command = MessageBreakAction(protocol, max_row, end)
action = QAction(self.command.text(), parent)
action.triggered.connect(self.action_triggered)
self.undo_stack = undo_stack
return action
def set_databaseconnection():
'''
Setting connection with SQLite
'''
# TODO explicitly close database connection on exit
filepath = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'ResourceFiles', 'Database', 'Intg_osdag.sqlite')
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(filepath)
if not db.open():
QMessageBox.critical(None, qApp.tr("Cannot open database"),
qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n"
"Click Cancel to exit."),
QMessageBox.Cancel)
return False
def showDocInAssistant(self, name):
url = self.resolveDocUrl(name)
Colors.debug("Sending URL to Assistant:", url)
# Start assistant if it's not already running.
if self.assistantProcess.state() != QProcess.Running:
app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator()
if sys.platform == 'darwin':
app += 'Assistant.app/Contents/MacOS/Assistant'
else:
app += 'assistant'
args = ['-enableRemoteControl']
self.assistantProcess.start(app, args)
if not self.assistantProcess.waitForStarted():
QMessageBox.critical(None, "PyQt Demo",
"Could not start %s." % app)
return
# Send command through remote control even if the process was just
# started to activate assistant and bring it to the front.
cmd_str = QTextStream(self.assistantProcess)
cmd_str << 'SetSource ' << url << '\n'
def validateSystem(self):
"""
Orders the AppController to validate a model based on the selected database.
Parameters
----------
None
Return
----------
None
"""
if self.path_validate:
checked, validated, accuracy, precision, sensitivity, specificity, kappa = self.controller.validate(self.path_validate, self.spinBoxFolds.value(), self.comboBoxDatabaseValidate.currentText())
self.path_validate = None
if not validated:
QMessageBox.warning(self.validate, "Message", "Classifier for "+ self.comboBoxDatabaseValidate.currentText() + " database is not trained.")
self.clearValidateLineEdits()
else:
self.lineEditAccuracy.setText(str(accuracy))
self.lineEditPrecision.setText(str(precision))
self.lineEditSensitivity.setText(str(sensitivity))
self.lineEditSpecificity.setText(str(specificity))
self.lineEditKappa.setText(str(kappa))
QMessageBox.information(self.train, "Message", "Validation finished.")
if not checked:
QMessageBox.critical(self.validate, "Message", "File columns or labels mismatch.")
self.clearValidateLineEdits()
else:
QMessageBox.warning(self.validate, "Message", "Must pick a database file.")
self.clearValidateLineEdits()
def _save_local(self):
path = self.localPathEdit.text()
if not path:
QMessageBox.warning(self, "Invalid path", "Enter correct path for local file.")
return
try:
with open(path, "w") as file:
file.write(self.codeEdit.toPlainText())
except IOError:
QMessageBox.critical(self, "Save operation failed", "Couldn't save the file. Check path and permissions.")
def _flash_finished(self, code):
Logger.log("Flash output contents:\r\n")
Logger.log(self._flash_output)
if code == 0:
self._flash_output.extend(b"Rebooting from flash mode...\n")
self._update_output()
try:
s = serial.Serial(self._port, 115200)
s.dtr = False
s.rts = True
time.sleep(0.1)
s.rts = False
time.sleep(0.1)
self._flash_output.extend(b"Done, you may now use the device.\n")
self._update_output()
except (OSError, serial.SerialException):
QMessageBox.critical(self, "Flashing Error", "Failed to reboot into working mode.")
elif code == -1:
QMessageBox.critical(self, "Flashing Error", "Failed to run script.\nCheck that path to python is correct.")
else:
QMessageBox.critical(self, "Flashing Error", "Failed to flash new firmware")
self.eraseButton.setEnabled(True)
self.flashButton.setEnabled(True)
self._flashing = False
def cmd_error(self, error: QProcess.ProcessError) -> None:
if error != QProcess.Crashed:
QMessageBox.critical(self.parent, 'Error calling an external process',
self.proc.errorString(), buttons=QMessageBox.Close)
def get_hoster_links(self) -> None:
try:
req = self.scraper.get(self.link_url, proxies=self.proxy)
bs = BeautifulSoup(req.text, 'lxml')
links = bs.select('div.post h2[style="text-align: center;"]')
self.setHosters.emit(links)
except HTTPError:
print(sys.exc_info()[0])
QMessageBox.critical(self, 'ERROR NOTIFICATION', sys.exc_info()[0])
QThread.currentThread().quit()
except IndexError:
self.noLinks.emit()
QThread.currentThread().quit()
def file_opener(self, filename: str) -> None:
try:
if QFileInfo(filename).suffix() == 'vcp':
self.cutter.openProject(project_file=filename)
if filename == os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE):
os.remove(os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE))
else:
self.cutter.loadMedia(filename)
except (FileNotFoundError, PermissionError):
QMessageBox.critical(self, 'Error loading file', sys.exc_info()[0])
logging.exception('Error loading file')
qApp.restoreOverrideCursor()
self.restart()
def log_uncaught_exceptions(cls, exc, tb) -> None:
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(cls, exc))
def errorHandler(self, msg: str, title: str=None) -> None:
qApp.restoreOverrideCursor()
QMessageBox.critical(self, 'An error occurred' if title is None else title, msg, QMessageBox.Ok)
logging.error(msg)
def cmdError(self, error: QProcess.ProcessError) -> None:
if error != QProcess.Crashed:
QMessageBox.critical(self.parent, 'Error alert',
'<h4>{0} Error:</h4><p>{1}</p>'.format(self.backends.ffmpeg, self.proc.errorString()),
buttons=QMessageBox.Close)
# noinspection PyUnresolvedReferences, PyProtectedMember
def start(self):
key=self.textEdit.toPlainText()
page=self.comboBox.currentText()
if key:
os.system('redis-cli flushdb')
os.system('redis-cli lpush mycrawler:start_urls http://www.taobao.com')
os.system('scrapy crawl tb -a key='+str(key)+' -a page='+str(page)+'')
QMessageBox.critical(self,"??","?????")
else:
QMessageBox.critical(self,"??","?????????????")
return
#os.system('scrapy crawl jd -a key='+str(key)+' -a page='+str(page)+'')