def __init__(self): super(EjecutarWidget, self).__init__() layoutV = QVBoxLayout(self) layoutV.setContentsMargins(0, 0, 0, 0) layoutV.setSpacing(0) self.output = output_compiler.SalidaCompilador(self) layoutV.addWidget(self.output) self.setLayout(layoutV) # Flag self._compilation_failed = False # Procesos self.build_process = QProcess(self) if not sys.platform.startswith('linux'): self._envgcc = QProcessEnvironment.systemEnvironment() self._envgcc.insert("PATH", ENV_GCC) self.build_process.setProcessEnvironment(self._envgcc) self.execution_process = QProcess(self) # Conexiones self.build_process.readyReadStandardError.connect( self.output.stderr_output) self.build_process.finished[int, QProcess.ExitStatus].connect( self._compilation_finished) self.build_process.error[QProcess.ProcessError].connect( self._compilation_error) self.execution_process.finished[int, QProcess.ExitStatus].connect( self._execution_finished)
def __init__(self): super(EjecutarWidget, self).__init__() self.compilado = False self.tiempo = 0.0 layoutV = QVBoxLayout(self) layoutV.setContentsMargins(0, 0, 0, 0) layoutV.setSpacing(0) self.output = salida.SalidaCompilador(self) layoutV.addWidget(self.output) self.setLayout(layoutV) # Procesos self.proceso_compilacion = QProcess(self) self.proceso_ejecucion = QProcess(self) # Conexión self.output.ir_a_linea.connect(self._emitir_ir_a_linea) self.proceso_compilacion.readyReadStandardError.connect( self.output.parsear_salida_stderr) self.proceso_compilacion.finished[int, QProcess.ExitStatus].connect( self.ejecucion_terminada) self.proceso_compilacion.error[QProcess.ProcessError].connect( self._error_compilacion) self.proceso_ejecucion.error[QProcess.ProcessError].connect( self._ejecucion_terminada)
def run(self, scriptFile, args=None, env=None, wd=None): if self._proc: return self._proc = QProcess(self) if wd: self._proc.setWorkingDirectory(wd) if not env is None: self._env.update(env) envList = dict2qlst(self._env) if args is None: args = [] script = quote(scriptFile) if not os.path.exists(script): script = find_script(script) if not script or not os.path.exists(script): raise PublishException("Script '%s' cannot be found" % script) self._caller.handleScriptOutput("%s %s" % (scriptFile, ' '.join(args))) self._proc.setEnvironment(envList) self._proc.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self._proc, QtCore.SIGNAL("readyReadStandardOutput()"), self.readScriptOutput) QObject.connect(self._proc, QtCore.SIGNAL("finished(int, " \ "QProcess::ExitStatus)"), self.scriptFinished) self._proc.start(script, args, QIODevice.ReadOnly)
def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) vbox.setSpacing(0) vbox.setContentsMargins(0, 0, 0, 0) self.output = OutputWidget(self) hbox = QHBoxLayout() self.input = QLineEdit() self.lblInput = QLabel(self.tr("Input:")) vbox.addWidget(self.output) hbox.addWidget(self.lblInput) hbox.addWidget(self.input) vbox.addLayout(hbox) # process self.currentProcess = None self.__preScriptExecuted = False self._proc = QProcess(self) self._preExecScriptProc = QProcess(self) self._postExecScriptProc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self.output._refresh_output) self.connect(self._proc, SIGNAL("readyReadStandardError()"), self.output._refresh_error) self.connect(self._proc, SIGNAL("finished(int, QProcess::ExitStatus)"), self.finish_execution) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self.connect(self.input, SIGNAL("returnPressed()"), self.insert_input) self.connect(self._preExecScriptProc, SIGNAL("finished(int, QProcess::ExitStatus)"), self.__main_execution) self.connect(self._preExecScriptProc, SIGNAL("readyReadStandardOutput()"), self.output._refresh_output) self.connect(self._preExecScriptProc, SIGNAL("readyReadStandardError()"), self.output._refresh_error) self.connect( self._postExecScriptProc, SIGNAL("finished(int, QProcess::ExitStatus)"), self.__post_execution_message ) self.connect(self._postExecScriptProc, SIGNAL("readyReadStandardOutput()"), self.output._refresh_output) self.connect(self._postExecScriptProc, SIGNAL("readyReadStandardError()"), self.output._refresh_error)
def editPath(self, path, customTextEditor=None): """ Provides editing capability. :param path: Path to edit. :type path: unicode :param customTextEditor: Custom text editor. :type customTextEditor: unicode :return: Method success. :rtype: bool """ if customTextEditor: editCommand = self.getProcessCommand(path, customTextEditor) if editCommand: LOGGER.debug("> Current edit command: '{0}'.".format(editCommand)) LOGGER.info("{0} | Launching text editor with '{1}' path.".format(self.__class__.__name__, path)) editProcess = QProcess() editProcess.startDetached(editCommand) return True else: raise Exception("{0} | Exception raised: No suitable process command given!".format( self.__class__.__name__)) else: self.__scriptEditor.loadPath(path) and self.__scriptEditor.restoreDevelopmentLayout() return True
def __init__(self): QPlainTextEdit.__init__(self, u'>>> ') self.setUndoRedoEnabled(False) self.apply_editor_style() self.setToolTip(self.tr("Show/Hide (F4)")) self.moveCursor(QTextCursor.EndOfLine) self._patIsWord = re.compile('\w+') self.prompt = u'>>> ' self._console = console.Console() self._history = [] self._braces = None self.imports = ['import __builtin__'] self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import') self.patImport = re.compile('^(\\s)*import (\\w)+') self.patObject = re.compile('[^a-zA-Z0-9_\\.]') self.completer = completer_widget.CompleterWidget(self) self.okPrefix = QRegExp('[.)}:,\]]') #Create Context Menu self._create_context_menu() self._highlighter = highlighter.Highlighter(self.document(), 'python', resources.CUSTOM_SCHEME) self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line) self.highlight_current_line() self._proc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self._python_path_detected) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self._add_system_path_for_frozen()
def build(path): for name in os.listdir(path): source = os.path.join(path, name) target = None if source.endswith(".ui"): target = os.path.join(path, "ui_" + name.replace(".ui", ".py")) command = PYUIC4 elif source.endswith(".qrc"): target = os.path.join(path, "qrc_" + name.replace(".qrc", ".py")) command = PYRCC4 process = QProcess() if target is not None: if not os.access(target, os.F_OK) or ( os.stat(source)[stat.ST_MTIME] > os.stat(target)[stat.ST_MTIME]): args = ["-o", target, source] if Debug: print("# {0} -o {1} {2}".format(command, target, source)) else: process.start(command, args) if not process.waitForFinished(2 * 60 * 1000): print("failed", command, " ".join(args)) else: print(source, "->", target) elif Verbose: print(source, "is up-to-date")
def generate_frames(cls, input_file_path, output_dir, finish_callbak, frame_extension = "png"): file_name = input_file_path[input_file_path.rindex("/"):].replace(" ", "_") frames_output_path = output_dir+'/'+file_name if os.path.exists(frames_output_path): print "La cartella dei frame esiste gia, non avvio ffmpeg" finish_callbak(True, frames_output_path) else: #Create the folder os.makedirs(frames_output_path) #Execute FFMPEG def _check_callback_status(code, code2): print "Processo FFMpeg finito, chiamo la callback" finish_callbak(code==0, frames_output_path) process = QProcess(QApplication.instance()) process.finished.connect(_check_callback_status) #process.start("/usr/local/bin/ffmpeg", ['-i', input_file_path,'-t', '5', frames_output_path+'/Frame_%07d.'+frame_extension]) #process.start("/usr/local/bin/ffmpeg", ['-i', input_file_path, '-r', '30', '-t', '3', '-s', '213x120', '-ss', '00:01:30', frames_output_path+'/Frame_%07d.'+frame_extension]) process.start("/usr/local/bin/ffmpeg", ['-i', input_file_path, '-r', '15', '-t', '5', '-ss', '00:00:50', frames_output_path+'/Frame_%07d.'+frame_extension])
def editPath(self, path, customTextEditor=None): """ Provides editing capability. :param path: Path to edit. :type path: unicode :param customTextEditor: Custom text editor. :type customTextEditor: unicode :return: Method success. :rtype: bool """ if customTextEditor: editCommand = self.getProcessCommand(path, customTextEditor) if editCommand: LOGGER.debug( "> Current edit command: '{0}'.".format(editCommand)) LOGGER.info( "{0} | Launching text editor with '{1}' path.".format( self.__class__.__name__, path)) editProcess = QProcess() editProcess.startDetached(editCommand) return True else: raise Exception( "{0} | Exception raised: No suitable process command given!" .format(self.__class__.__name__)) else: self.__scriptEditor.loadPath( path) and self.__scriptEditor.restoreDevelopmentLayout() return True
class ProcessHostapd(QObject): statusAP_connected = pyqtSignal(object) def __init__(self,cmd): QObject.__init__(self) self.cmd = cmd def getNameThread(self): return 'Starting Thread:' + self.objectName() @pyqtSlot() def read_OutputCommand(self): self.data = str(self.procHostapd.readAllStandardOutput()) if 'AP-STA-DISCONNECTED' in self.data.rstrip() or 'inactivity (timer DEAUTH/REMOVE)' in self.data.rstrip(): self.statusAP_connected.emit(self.data.split()[2]) def start(self): print 'Starting Thread:' + self.objectName() self.makeLogger() self.procHostapd = QProcess(self) self.procHostapd.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procHostapd, SIGNAL('readyReadStandardOutput()'), self, SLOT('read_OutputCommand()')); self.procHostapd.start(self.cmd.keys()[0],self.cmd[self.cmd.keys()[0]]) def makeLogger(self): setup_logger('hostapd', './Logs/AccessPoint/requestAP.log') self.log_hostapd = logging.getLogger('hostapd') def stop(self): print 'Stop thread:' + self.objectName() if hasattr(self,'procHostapd'): self.procHostapd.terminate() self.procHostapd.waitForFinished() self.procHostapd.kill()
def run_installer(self, package_name): self.package_name = package_name if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] ## pip_rel_path = os.path.join(os.sep,'.qgis2', 'python', 'plugins','pipinstaller','pip-1.5.4') ## pip_path = ('%s%s') % (home,pip_rel_path) ## try: ## import pip ## except: ## try: ## subprocess.call('C:\\PROGRA~2\\QGISDU~1\\Osgeo4W.bat python ez_setup.py install') ## except Exception, e: ## print str(e) ## try: ## subprocess.call('C:\\PROGRA~2\\QGISDU~1\\Osgeo4W.bat python setup.py install') ## except Exception, e: ## print str(e) package_to_install = "reportlab" cmd = 'C:\\PROGRA~2\\QGISDU~1\\Osgeo4W.bat pip install sqlalchemy' qprocess = QProcess() p = qprocess.start(cmd) return p
def __init__(self, cmdline, sendername='qprocess'): self.cmdline = cmdline self.sendername = sendername self.leftover = b'' self.process = QProcess() self.process.readyRead.connect(self.on_ready_read) self.process.finished.connect(self.on_finished)
def viewImages(self, paths, customPreviewer=None): """ This method launches an Ibl Set Images Previewer. :param paths: Image paths. ( List ) :param customPreviewer: Custom previewer. ( String ) """ if customPreviewer: previewCommand = self.getProcessCommand(paths, customPreviewer) if previewCommand: LOGGER.debug("> Current image preview command: '{0}'.".format( previewCommand)) LOGGER.info( "{0} | Launching Previewer with '{1}' images paths.". format(self.__class__.__name__, ", ".join(paths))) editProcess = QProcess() editProcess.startDetached(previewCommand) return True else: raise Exception( "{0} | Exception raised: No suitable process command given!" .format(self.__class__.__name__)) else: if not len(self.__imagesPreviewers ) >= self.__maximumImagesPreviewersInstances: return self.getImagesPreviewer(paths) else: LOGGER.warning( "!> {0} | You can only launch '{1}' images Previewer instances at same time!" .format(self.__class__.__name__, self.__maximumImagesPreviewersInstances))
def start(self): filename = unicode(self.filecombo.currentText()) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setWorkingDirectory(osp.dirname(filename)) self.connect(self.process, SIGNAL("readyReadStandardOutput()"), self.read_output) self.connect(self.process, SIGNAL("readyReadStandardError()"), lambda: self.read_output(error=True)) self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"), self.finished) self.connect(self.stop_button, SIGNAL("clicked()"), self.process.kill) self.output = '' self.error_output = '' p_args = [osp.basename(filename)] self.process.start(PYLINT_PATH, p_args) running = self.process.waitForStarted() self.set_running_state(running) if not running: QMessageBox.critical( self, translate('Pylint', "Error"), translate('Pylint', "Process failed to start"))
class ThreadLogger(QObject): def __init__(self, logger_path=str): QObject.__init__(self) self.logger_path = logger_path @pyqtSlot() def readProcessOutput(self): try: self.emit( SIGNAL('Activated( QString )'), str(self.procLogger.readAllStandardOutput()).rstrip().split( ' : ')[1]) except Exception: pass def start(self): self.procLogger = QProcess(self) self.procLogger.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procLogger, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procLogger.start('tail', ['-f', self.logger_path]) def stop(self): if hasattr(self, 'procLogger'): self.procLogger.terminate() self.procLogger.waitForFinished() self.procLogger.kill()
def build_iso(self, directory, iso_file): if self.process: return directory = os.path.abspath(directory) iso_file = os.path.abspath(iso_file) self.progress = QProgressDialog("Building ISO...", QtCore.QString(), 0, 0, self.parent) self.progress.setWindowTitle("Building ISO") self.progress.setWindowModality(Qt.Qt.WindowModal) self.progress.setAutoClose(False) self.progress.setMinimumDuration(1000) self.progress.show() self.progress.setValue(0) self.progress.setMaximum(100) self.process = QProcess() self.process.finished.connect(self.__build_finished) self.process.setReadChannel(QProcess.StandardError) self.process.readyRead.connect(self.__parse_output) self.process.start("tools/mkisofs", [ "-sort", "data/file_order.txt", "-iso-level", "4", "-xa", "-A", "PSP GAME", "-V", "DANGANRONPA", "-sysid", "PSP GAME", "-volset", "DANGANRONPA", "-p", "SPIKE", "-publisher", "SPIKE", "-o", iso_file, directory ])
def __init__(self, parent, title, cmd_list, obj_directory="", start_directory=""): """ Constructor """ QDialog.__init__(self, parent) Ui_CFDSTUDYGUI_QProcessDialog.__init__(self) self.setupUi(self) self.setWindowTitle(title) self.pushButton.setEnabled(False) if start_directory != None and start_directory != "": os.chdir(start_directory) self.objBr = None if obj_directory != None and obj_directory != "": self.objBr = obj_directory self.proc = QProcess() #env = QProcessEnvironment().systemEnvironment() #self.proc.setProcessEnvironment(env) self.connect(self.proc, SIGNAL('readyReadStandardOutput()'), self.__readFromStdout) self.connect(self.proc, SIGNAL('readyReadStandardError()'), self.__readFromStderr) self.procErrorFlag = False self.cmd_list = cmd_list self.cmd = self.cmd_list.pop(0) cursor = QCursor(Qt.BusyCursor) QApplication.setOverrideCursor(cursor) self.__process()
def __init__(self): super(ConsoleWidget, self).__init__('>>> ') self.setUndoRedoEnabled(False) self.apply_editor_style() self.setToolTip(self.tr("Show/Hide (F4)")) self.moveCursor(QTextCursor.EndOfLine) self._patIsWord = re.compile('\w+') self.prompt = '>>> ' self._console = console.Console() self._history = [] self.history_index = 0 self._current_command = '' self._braces = None self.imports = ['import __builtin__'] self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import') self.patImport = re.compile('^(\\s)*import (\\w)+') self.patObject = re.compile('[^a-zA-Z0-9_\\.]') #self.completer = completer_widget.CompleterWidget(self) self.okPrefix = QRegExp('[.)}:,\]]') self._pre_key_press = { Qt.Key_Enter: self._enter_pressed, Qt.Key_Return: self._enter_pressed, Qt.Key_Tab: self._tab_pressed, Qt.Key_Home: self._home_pressed, Qt.Key_PageUp: lambda x: True, Qt.Key_PageDown: lambda x: True, Qt.Key_Left: self._left_pressed, Qt.Key_Up: self._up_pressed, Qt.Key_Down: self._down_pressed, Qt.Key_Backspace: self._backspace, } #Create Context Menu self._create_context_menu() #Set Font self.set_font(settings.FONT) #Create Highlighter parts_scanner, code_scanner, formats = \ syntax_highlighter.load_syntax(python_syntax.syntax) self.highlighter = syntax_highlighter.SyntaxHighlighter( self.document(), parts_scanner, code_scanner, formats) self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line) self.highlight_current_line() self._proc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self._python_path_detected) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self._add_system_path_for_frozen() ninjaide = IDE.get_service('ide') self.connect(ninjaide, SIGNAL("ns_preferences_editor_font(PyQt_PyObject)"), self.set_font)
def NBR_render(self): global folderQueue for nk in xrange(len(folderQueue)): renderNode = [] # proj = os.path.splitext(os.path.basename(folderQueue[nk]))[0] projDict = self.NBR_getCellData(nk, 0, 'Project') if int(projDict['Project']) > 0: nodeArr = self.NBR_getCellNodeData(nk, 1) startDict = self.NBR_getCellData(nk, 2, 'Start') endDict = self.NBR_getCellData(nk, 3, 'End') # Write nodes loop for node in xrange(len(nodeArr)): if nodeArr[node][1] > 0: # get each node check state (0/2), selected write node (render) renderNode.append(nodeArr[node][0].split(":")[0]) # Debug print str(renderNode) # print nodeArr self.nukeProcess = QProcess(self) # QProcess for nuke print nodeArr[node][0].split(":")[0] # get each node from array self.nukeProcess.setProcessChannelMode(QProcess.MergedChannels) args = self.createCmdArg2(str(folderQueue[nk]), renderNode, startDict['Start'], endDict['End']) self.nukeProcess.start(NUKE_EXE, str(args)) self.nukeProcess.readyRead.connect(self.NBR_debug) self.nukeProcess.waitForFinished() self.nukeProcess.close()
def do_pylint(self): """ Launch the lint process and create the result window """ print 'do_pylint' self.pylint_pross = QProcess() self.pylint_pross.setProcessChannelMode(QProcess.MergedChannels) self.pylint_pross.setWorkingDirectory( \ os.path.dirname(str(self.parent.editor.filename))) self.pylint_pross.setReadChannel(QProcess.StandardOutput) self.connect(self.pylint_pross, \ SIGNAL('finished(int)'), \ self.finished) self.connect(self.pylint_pross, \ SIGNAL('readyReadStandardOutput()'), \ self.handle_stdout) self.connect(self.pylint_pross, \ SIGNAL('readyReadStandardError()'), \ self.handle_stderr) if (self.pylint_pross.start("pylint", \ [self.parent.editor.filename,])): print 'Cannot start process' self.win = ResultWin() self.win.setWindowTitle("PyLint Results :" \ + os.path.basename(str(self.parent.editor.filename))) self.win.show() if isMAEMO: self.win.setAttribute(Qt.WA_Maemo5ShowProgressIndicator, True) self.win.connect(self.win.list_view, \ SIGNAL('doubleClicked(const QModelIndex&)'), \ self.goto_line) self.pylint_pross.waitForStarted()
def viewImages(self, paths, customPreviewer=None): """ This method launches an Ibl Set Images Previewer. :param paths: Image paths. ( List ) :param customPreviewer: Custom previewer. ( String ) """ if customPreviewer: previewCommand = self.getProcessCommand(paths, customPreviewer) if previewCommand: LOGGER.debug("> Current image preview command: '{0}'.".format(previewCommand)) LOGGER.info("{0} | Launching Previewer with '{1}' images paths.".format(self.__class__.__name__, ", ".join(paths))) editProcess = QProcess() editProcess.startDetached(previewCommand) return True else: raise Exception("{0} | Exception raised: No suitable process command given!".format( self.__class__.__name__)) else: if not len(self.__imagesPreviewers) >= self.__maximumImagesPreviewersInstances: return self.getImagesPreviewer(paths) else: LOGGER.warning("!> {0} | You can only launch '{1}' images Previewer instances at same time!".format( self.__class__.__name__, self.__maximumImagesPreviewersInstances))
def open_with(app, file): """Open file with app.""" if sys.platform == "darwin": QProcess.startDetached("open", [file, "-a", app]) else: QProcess.startDetached(app, [file])
def process_file(self): """ Converts PDF pages to tif files, Uses ghostscript from the command line """ process = QProcess() process.start(' '.join([ self.gscriptpath + '\gswin32c.exe"', #gs exe '-q', '-dNOPAUSE', '-dBATCH', # resolution/dpi '-r{0}x{0}'.format(self.res), # container type, see gs docs '-sDEVICE={0}'.format(self.mode), '-sPAPERSIZE=a4', # page size '-sOutputFile=%s %s' % (str(self.ofname), str(self.ifname))])) # don't spawn cmd window process.waitForFinished(-1)
def start(self): self.makeLogger() self.procHostapd = QProcess(self) self.procHostapd.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procHostapd, SIGNAL('readyReadStandardOutput()'), self, SLOT('read_OutputCommand()')); self.procHostapd.start(list(dict(self.cmd).keys())[0],self.cmd[list(dict(self.cmd).keys())[0]]) print('[New Thread {} ({})]'.format(self.procHostapd.pid(),self.objectName()))
def start(self): self.setIptables(self.APmode,option='A') self.procThreadDNS = QProcess(self) self.procThreadDNS.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThreadDNS, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThreadDNS.start('python',['core/packets/dnsspoofNF.py','-r',self.redirect, '-d',','.join(self.domains)])
def __init__(self): self.process = QProcess() self.process.error[QProcess.ProcessError].connect( self.error_management) self.env = QProcessEnvironment().systemEnvironment() self.set_otb_process_env_default() self.command = ""
def setOptions(self, colormode_index, quality_index, papertype_index, papersize_index, custom_size=[]): color_mode = self.color_modes[colormode_index] quality = self.quality_modes[quality_index] paper_type = self.paper_types[papertype_index] paper_size = self.paper_sizes[papersize_index] if paper_size == 'Custom.WIDTHxHEIGHT': paper_size = 'Custom.%ix%imm' % (custom_size[0], custom_size[1]) lpoptions_args = [ '-p', self.printer, '-o', 'ColorModel=' + color_mode, '-o', 'cupsPrintQuality=' + quality, '-o', "MediaType=" + paper_type, '-o', 'PageSize=' + paper_size ] print('lpoptions', ' '.join(lpoptions_args)) process = QProcess() process.start('lpoptions', lpoptions_args) if not process.waitForFinished(): print("Error : Could not execute lpoptions") return False return True
class ThreadDNSspoofNF(QObject): DnsReq = pyqtSignal(object) def __init__(self,domains,interface,redirect,APmode=True,parent=None): super(ThreadDNSspoofNF, self).__init__(parent) self.domains = domains self.interface = interface self.redirect = redirect self.APmode = APmode self.desc = 'DNS spoof Module::NetFilter' @pyqtSlot() def readProcessOutput(self): self.data = str(self.procThreadDNS.readAllStandardOutput()) self.DnsReq.emit(self.data) def start(self): self.setIptables(self.APmode,option='A') self.procThreadDNS = QProcess(self) self.procThreadDNS.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThreadDNS, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThreadDNS.start('python',['core/packets/dnsspoofNF.py','-r',self.redirect, '-d',','.join(self.domains)]) def setIptables(self,APMode=True, option=str()): if APMode: system('iptables -{} INPUT -i {} -p udp --dport 53 -s {} -j ACCEPT'.format(option,self.interface,self.redirect)) system('iptables -{} INPUT -i {} -p udp --dport 53 -j DROP'.format(option,self.interface)) system('iptables -t nat -{} PREROUTING -p udp --dport 53 -j NFQUEUE'.format(option)) def stop(self): self.setIptables(self.APmode,option='D') if hasattr(self,'procThreadDNS'): self.procThreadDNS.terminate() self.procThreadDNS.waitForFinished() self.procThreadDNS.kill()
def __pack_cpk(self, csv, cpk): self.progress.setValue(0) self.progress.setMaximum(1000) self.progress.setLabelText("Building %s" % cpk) process = QProcess() process.start("tools/cpkmakec", [csv, cpk, "-align=2048", "-mode=FILENAME"]) percent = 0 while not process.waitForFinished(100): output = QString(process.readAll()) output = output.split("\n", QString.SkipEmptyParts) for line in output: line = common.qt_to_unicode(line) match = OUTPUT_RE.search(line) if match == None: continue percent = float(match.group(1)) * 1000 self.progress.setValue(percent) percent += 1
def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) vbox.setSpacing(0) vbox.setContentsMargins(0, 0, 0, 0) self.output = OutputWidget(self) hbox = QHBoxLayout() self.input = QLineEdit() self.lblInput = QLabel(self.tr("Input:")) vbox.addWidget(self.output) hbox.addWidget(self.lblInput) hbox.addWidget(self.input) vbox.addLayout(hbox) #process self._proc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self.output._refresh_output) self.connect(self._proc, SIGNAL("readyReadStandardError()"), self.output._refresh_error) self.connect(self._proc, SIGNAL("finished(int, QProcess::ExitStatus)"), self.finish_execution) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self.connect(self.input, SIGNAL("returnPressed()"), self.insert_input)
class ProcessThread(QObject): def __init__(self,cmd,): QObject.__init__(self) self.cmd = cmd def getNameThread(self): return 'Starting Thread:' + self.objectName() @pyqtSlot() def readProcessOutput(self): self.data = str(self.procThread.readAllStandardOutput()) def start(self): print 'Starting Thread:' + self.objectName() self.procThread = QProcess(self) self.procThread.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThread, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThread.start(self.cmd.keys()[0],self.cmd[self.cmd.keys()[0]]) def stop(self): print 'Stop thread:' + self.objectName() if hasattr(self,'procThread'): self.procThread.terminate() self.procThread.waitForFinished() self.procThread.kill()
def build(path): for name in os.listdir(path): source = os.path.join(path, name) target = None if source.endswith(".ui"): target = os.path.join(path, "ui_" + name.replace(".ui", ".py")) command = PYUIC4 elif source.endswith(".qrc"): target = os.path.join(path, "qrc_" + name.replace(".qrc", ".py")) command = PYRCC4 process = QProcess() if target is not None: if not os.access(target, os.F_OK) or (os.stat(source)[stat.ST_MTIME] > os.stat(target)[stat.ST_MTIME]): args = ["-o", target, source] if Debug: print("# {0} -o {1} {2}".format(command, target, source)) else: process.start(command, args) if not process.waitForFinished(2 * 60 * 1000): print("failed", command, " ".join(args)) else: print(source, "->", target) elif Verbose: print(source, "is up-to-date")
def __init__(self, name, project, **kwargs): super(BatchFileSync, self).__init__(name, project) self.cmd = kwargs['cmd'] if self.project: self.rootfolder = os.path.abspath(self.project.folder) else: self.rootfolder = kwargs['rootfolder'] self.project = project self.closeproject = kwargs.get("close_project", False) self.process = QProcess() self.parser = kwargs.get("parser", None) self.parsermodule = None variables = kwargs.get("variables", {}) env = QProcessEnvironment.systemEnvironment() for varname, value in variables.iteritems(): env.insert(varname, str(value)) self.process.setProcessEnvironment(env) self.process.setWorkingDirectory( os.path.dirname(os.path.realpath(self.cmd))) self.process.finished.connect(self.complete) self.process.started.connect(self.syncStarted) self.process.readyReadStandardError.connect(self.error) self.process.readyReadStandardOutput.connect(self.readOutput) self._output = "" self.haserror = False
class ThreadDNSspoofNF(QObject): DnsReq = pyqtSignal(object) def __init__(self,domains,interface,redirect,APmode=True,parent=None): super(ThreadDNSspoofNF, self).__init__(parent) self.domains = domains self.interface = interface self.redirect = redirect self.APmode = APmode self.desc = 'DNS spoof Module::NetFilter' @pyqtSlot() def readProcessOutput(self): self.data = str(self.procThreadDNS.readAllStandardOutput()) self.DnsReq.emit(self.data) def start(self): self.setIptables(self.APmode,option='A') self.procThreadDNS = QProcess(self) self.procThreadDNS.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThreadDNS, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThreadDNS.start('python',['Core/packets/dnsspoofNF.py','-r',self.redirect, '-d',','.join(self.domains)]) def setIptables(self,APMode=True, option=str()): if APMode: system('iptables -{} INPUT -i {} -p udp --dport 53 -s {} -j ACCEPT'.format(option,self.interface,self.redirect)) system('iptables -{} INPUT -i {} -p udp --dport 53 -j DROP'.format(option,self.interface)) system('iptables -t nat -{} PREROUTING -p udp --dport 53 -j NFQUEUE'.format(option)) def stop(self): self.setIptables(self.APmode,option='D') if hasattr(self,'procThreadDNS'): self.procThreadDNS.terminate() self.procThreadDNS.waitForFinished() self.procThreadDNS.kill()
class Common(base.Common): def systemSettingsButton(self): self.procSettings = QProcess() self.procSettings.start("systemsettings") def getLanguage(self): lang = KGlobal.locale().language() return lang
def start(self): self.procThread = QProcess(self) self.procThread.setProcessChannelMode(QProcess.MergedChannels) if self.directory_exec: self.procThread.setWorkingDirectory(self.directory_exec) QObject.connect(self.procThread, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThread.start(list(dict(self.cmd).keys())[0],self.cmd[list(dict(self.cmd).keys())[0]]) print('[New Thread {} ({})]'.format(self.procThread.pid(),self.objectName()))
def cim2modelica(self): command = "java" args = ["-jar", "./lib/cim2modelica.jar", self.txtEQ.text(), self.txtTP.text(), self.txtSV.text(), self.txtDY.text(), self.txtModelName.text(), str(self.cbxCimSchema.currentText())] process = QProcess(self) process.finished.connect(self.onFinished) process.start(command, args)
def start(self): self.procThread = QProcess(self) self.procThread.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThread, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThread.start(self.cmd.keys()[0], self.cmd[self.cmd.keys()[0]]) print '[New Thread {} ({})]'.format(self.procThread.pid(), self.objectName())
def connect(self, parent_window=None): if not parent_window is None: setattr(self._cfg, 'parent-window', parent_window) self._conn = QProcess() # print(self._cfg.as_list()) self._conn.start('xfreerdp', self._cfg.as_list()) self._conn.readyReadStandardOutput.connect(self._read_out) self._conn.readyReadStandardError.connect(self._read_err)
def __init__(self, locator): QMenu.__init__(self, 'Plugin Tools') self._locator = locator self.explorer_s = self._locator.get_service('explorer') self._proc = QProcess(self) action_zip = self.addAction('Package This Plugin!') self.connect(action_zip, SIGNAL("triggered()"), self.create_zip) action_run = self.addAction('Test This Plugin on NINJA-IDE!') self.connect(action_run, SIGNAL("triggered()"), self.run_plugin)
def witProcess(self): self.createButton.setEnabled(0) self.createButton.setText("Please Wait") os.chdir(module_path(), 'wit') command = "wit.exe" args = ["copy", fstPath, "testdisc.wbfs", "--overwrite"] # "--verbose", "--progress" process = QProcess(self) process.finished.connect(self.onFinished) process.startDetached(command, args)
def __init__(self, parent, xterm_cmd="xterm"): QX11EmbedContainer.__init__(self, parent) self.xterm_cmd = xterm_cmd self.process = QProcess(self) self.connect(self.process, SIGNAL("finished(int, QProcess::ExitStatus)"), self.on_term_close) atexit.register(self.kill) self.show_term()
def fetchOutputForJob(self): self.process = QProcess() self.process.readyReadStandardOutput.connect(self.writeStdout) self.process.readyReadStandardError.connect(self.writeStderr) print(" Please wait, running tests", end=' ') sys.stdout.flush() self.process.start(self.testfile, ["-maxwarnings", "0"]) self.process.waitForFinished(-1) return str(self.data)
def auto_spice(self): serverIp = "192.168.0.29" #serverIp = "192.168.1.32" argcList = ["smep://%s/?port=%s" % (serverIp, "5901")] if self.flag: print "argcList:%s" % argcList self.flag = False os.system("killall window") QProcess.startDetached("/opt/ccr-student/window/window", argcList)
class IsoBuilder(): def __init__(self, parent=None): self.parent = parent self.process = None def __parse_output(self): if not self.process: return output = QString(self.process.readAll()) output = output.split("\n", QString.SkipEmptyParts) for line in output: line = common.qt_to_unicode(line) match = OUTPUT_RE.match(line) if match == None: continue percent = float(match.group(1)) self.progress.setValue(percent) def build_iso(self, directory, iso_file): if self.process: return directory = os.path.abspath(directory) iso_file = os.path.abspath(iso_file) self.progress = QProgressDialog("Building ISO...", QtCore.QString(), 0, 0, self.parent) self.progress.setWindowTitle("Building ISO") self.progress.setWindowModality(Qt.Qt.WindowModal) self.progress.setAutoClose(False) self.progress.setMinimumDuration(1000) self.progress.show() self.progress.setValue(0) self.progress.setMaximum(100) self.process = QProcess() self.process.finished.connect(self.__build_finished) self.process.setReadChannel(QProcess.StandardError) self.process.readyRead.connect(self.__parse_output) self.process.start("tools/mkisofs", [ "-sort", "data/file_order.txt", "-iso-level", "4", "-xa", "-A", "PSP GAME", "-V", "DANGANRONPA", "-sysid", "PSP GAME", "-volset", "DANGANRONPA", "-p", "SPIKE", "-publisher", "SPIKE", "-o", iso_file, directory ]) def __build_finished(self, code, status): self.progress.close() self.process = None
class Common(base.Common): def getLanguage(self): locale_app = QLocale() locale_os = QLocale.system() info = [] var = QLocale.languageToString(locale_app.language()) return var def systemSettingsButton(self): self.procSettings = QProcess() self.procSettings.start("gnome-control-center")
class Common(base.Common): def getLanguage(self): locale_app = QLocale() locale_os = QLocale.system() info = [] var = QLocale.languageToString(locale_app.language()) return var def on_buttonSystemSettings_clicked(self): self.procSettings = QProcess() # TODO: fix program self.procSettings.start("program name")
class IsoBuilder(): def __init__(self, parent = None): self.parent = parent self.process = None def __parse_output(self): if not self.process: return output = QString(self.process.readAll()) output = output.split("\n", QString.SkipEmptyParts) for line in output: line = common.qt_to_unicode(line) match = OUTPUT_RE.match(line) if match == None: continue percent = float(match.group(1)) self.progress.setValue(percent) def build_iso(self, directory, iso_file): if self.process: return directory = os.path.abspath(directory) iso_file = os.path.abspath(iso_file) self.progress = QProgressDialog("Building ISO...", QtCore.QString(), 0, 0, self.parent) self.progress.setWindowTitle("Building ISO") self.progress.setWindowModality(Qt.Qt.WindowModal) self.progress.setAutoClose(False) self.progress.setMinimumDuration(1000) self.progress.show() self.progress.setValue(0) self.progress.setMaximum(100) self.process = QProcess() self.process.finished.connect(self.__build_finished) self.process.setReadChannel(QProcess.StandardError) self.process.readyRead.connect(self.__parse_output) self.process.start("tools/mkisofs", ["-sort", "data/file_order.txt", "-iso-level", "4", "-xa", "-A", "PSP GAME", "-V", "DANGANRONPA", "-sysid", "PSP GAME", "-volset", "DANGANRONPA", "-p", "SPIKE", "-publisher", "SPIKE", "-o", iso_file, directory]) def __build_finished(self, code, status): self.progress.close() self.process = None
class Rabisk(QtGui.QMainWindow): text="peganingas" pic=None def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.layers = [] self.canvasWidth = 640 # size of image, not entire widget self.canvasHeight = 480 self.ui.label.setGeometry(QtCore.QRect(0, 0, 66, 17)) print self.ui.centralwidget.width #self.ui.label.geometry.Width=self.ui.geometry.Width #self.ui.label.height=self.ui.height self.setWindowState(Qt.WindowFullScreen) print self.ui.centralwidget.width() self.ui.label.setGeometry(QtCore.QRect(0, 0, self.ui.centralwidget.width(), self.ui.centralwidget.height())) self.pic=QPixmap(self.ui.centralwidget.width(), self.ui.centralwidget.height()) self.camera=QProcess(self) self.camera.readyReadStandardOutput.connect(self.handle_stdout) self.camera.start('python sense.py') self.show() def paintEvent(self, event): print "drawing" qp=QtGui.QPainter() qp.begin(self) qp.setPen(QtGui.QColor(1,10,0)) qp.drawText(10,10, self.text) qp.end() def handle_stdout(self): byteArray=self.camera.readAllStandardOutput() data=re.sub(r'''\n+$''', "", byteArray.data()) print data self.text=data #self.ui.label.setText("whatever"+data); qp=QtGui.QPainter(self.pic) qp.setPen(QtGui.QColor(1,10,0)) qp.drawText(100,10, self.text) self.ui.label.setPixmap(self.pic) def keyPressEvent(self, e): k=e.key() print e.key()
def run(cmd, args=[]): """Executes the command `cmd` with optional arguments `args`, provided it is available on the system. Parameters: - `cmd`: The program command. - `args`: a list of arguments to pass to `cmd` (default is []). """ if not dryrun: proc = QProcess() proc.start(cmd, args) while proc.waitForReadyRead(): if verbose: print '>>>' print 'ReadyRead:\n{0}'.format(proc.readAll()) print '<<<' if verbose: stderr = proc.readAllStandardError() if stderr != '': print '>>>' print 'Errors:\n{0}'.format(stderr) print '<<<' stdout = proc.readAllStandardOutput() if stdout != '': print '>>>' print 'Output:{0}\n'.format(proc.readAllStandardOutput()) print '<<<'
def __init__(self): QThread.__init__(self) self.process = QProcess() self.cmd = None self.process.readyReadStandardOutput.connect(self.readOutput) self.process.readyReadStandardError.connect(self.readErrors) self.process.finished.connect(self.fini)
def start(self): self.setIptables(self.APmode,option='A') self.procThreadDNS = QProcess(self) self.procThreadDNS.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procThreadDNS, SIGNAL('readyReadStandardOutput()'), self, SLOT('readProcessOutput()')) self.procThreadDNS.start('python',['Core/packets/dnsspoofNF.py','-r',self.redirect, '-d',','.join(self.domains)])
def __init__(self, parent=None): super(Dlg, self).__init__(parent) self.setupUi(self) self.dockWidget.hide() self.fileLineEdit.setDisabled(True) self.fileButton.setDisabled(True) self.closeButton.clicked.connect(self.close) self.buildButton.clicked.connect(self.build) self.fileButton.clicked.connect(self.getFile) self.fileRadioButton.toggled.connect(self.fileLineEdit.setEnabled) self.fileRadioButton.toggled.connect(self.fileButton.setEnabled) self.logButton.toggled.connect(self.dockWidget.setVisible) for button in (self.sourceButton, self.outputButton): button.clicked.connect(self.getDirectory) self.sourceDirectory = None self.outputDirectory = None self.process = QProcess() self.process.readyReadStandardOutput.connect(self.readOutput) self.process.readyReadStandardError.connect(self.readErrors) #restore settings settings = QSettings() size = settings.value('Dialog/Size', QVariant(QSize(600, 500))).toSize() self.resize(size) pos = settings.value('Dialog/Position', QVariant(QPoint(0, 0))).toPoint() self.move(pos) for widget, setting in ((self.sourceLineEdit, 'Data/SourceDirectory'), (self.outputLineEdit, 'Data/OutputDirectory')): widget.setText(settings.value(setting).toString())
def start(self): self.makeLogger() self.procHostapd = QProcess(self) self.procHostapd.setProcessChannelMode(QProcess.MergedChannels) QObject.connect(self.procHostapd, SIGNAL('readyReadStandardOutput()'), self, SLOT('read_OutputCommand()')); self.procHostapd.start(self.cmd.keys()[0],self.cmd[self.cmd.keys()[0]]) print '[New Thread {} ({})]'.format(self.procHostapd.pid(),self.objectName())
def __init__(self, parent, iface, pluginBase, pluginName, pluginCommand): QDialog.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.iface = iface self.process = QProcess(self) Utils.setProcessEnvironment(self.process) self.connect(self.process, SIGNAL("error(QProcess::ProcessError)"), self.processError) self.connect(self.process, SIGNAL("finished(int, QProcess::ExitStatus)"), self.processFinished) self.setupUi(self) self.arguments = [] self.editCmdBtn.setIcon(QIcon(":/icons/edit.png")) self.connect(self.editCmdBtn, SIGNAL("toggled(bool)"), self.editCommand) self.resetCmdBtn.setIcon(QIcon(":/icons/reset.png")) self.connect(self.resetCmdBtn, SIGNAL("clicked()"), self.resetCommand) self.editCommand(False) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept) self.connect(self.buttonBox, SIGNAL("helpRequested()"), self.help) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True) self.plugin = pluginBase self.connect(self.plugin, SIGNAL("valuesChanged(PyQt_PyObject)"), self.refreshArgs) self.pluginLayout.addWidget(self.plugin) self.plugin.setFocus() self.setWindowTitle(pluginName) self.setPluginCommand(pluginCommand)
def __init__(self, name, project, **kwargs): super(BatchFileSync, self).__init__(name, project) self.cmd = kwargs['cmd'] if self.project: self.rootfolder = os.path.abspath(self.project.folder) else: self.rootfolder = kwargs['rootfolder'] self.project = project self.closeproject = kwargs.get("close_project", False) self.process = QProcess() self.parser = kwargs.get("parser", None) self.parsermodule = None variables = kwargs.get("variables", {}) env = QProcessEnvironment.systemEnvironment() for varname, value in variables.iteritems(): env.insert(varname, str(value)) self.process.setProcessEnvironment(env) self.process.setWorkingDirectory(os.path.dirname(os.path.realpath(self.cmd))) self.process.finished.connect(self.complete) self.process.started.connect(self.syncStarted) self.process.readyReadStandardError.connect(self.error) self.process.readyReadStandardOutput.connect(self.readOutput) self._output = "" self.haserror = False
def toggleProcess(self, val): if val: print 'Starting process' self.status, self.pid = QProcess.startDetached(self.command, self.args, '.') if self.status: print 'PID: ', self.pid pidFile = open(self.pidFilePath, 'w') pidFile.write(str(self.pid)) pidFile.close() self.qbtn.setText('Stop') else: self.qbtn.setChecked(False) print 'Error: Failed to create process!' else: print 'Stopping process' if self.status: # kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI try: os.kill(self.pid, SIGINT) print 'Process stopped!' self.status = False self.pid = 0 if os.path.isfile(self.pidFilePath): os.remove(self.pidFilePath) else: print 'Error: No PID file with selected name found' self.qbtn.setText('Start') except OSError as e: # http://linux.die.net/man/3/kill | see section "Errors" if e.errno == 3: # process was not found print 'Error: Process with selected PID not found' os.remove(self.pidFilePath) else: print 'Error: Not enough permissions to terminate' self.qbtn.setChecked(True)