class BatchFileSync(SyncProvider): def __init__(self, name, **kwargs): super(BatchFileSync, self).__init__(name) self.cmd = kwargs['cmd'] self.process = QProcess() variables = kwargs.get("variables", {}) env = QProcessEnvironment.systemEnvironment() for varname, value in variables.iteritems(): env.insert(varname, 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 start(self): self._output = "" self.process.start(self.cmd, []) @property def output(self): return self._output @output.setter def output(self, value): self._output = value def error(self): self.haserror = True def complete(self, error, status): if error > 0: stderr = self.process.readAllStandardError().data() self.syncError.emit(stderr) else: self.syncComplete.emit() self.syncFinished.emit() def readOutput(self): output = str(self.process.readAll()) self.syncMessage.emit(output)
class RunWidget(QWidget): """Widget that show the execution output in the MiscContainer.""" 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 process_error(self, error): """Listen to the error signals from the running process.""" self.lblInput.hide() self.input.hide() self._proc.kill() format_ = QTextCharFormat() format_.setAnchor(True) format_.setForeground(Qt.red) if error == 0: self.output.textCursor().insertText(self.tr('Failed to start'), format_) else: self.output.textCursor().insertText( self.tr('Error during execution, QProcess error: %d' % error), format_) def finish_execution(self, exitCode, exitStatus): """Print a message and hide the input line when the execution ends.""" self.lblInput.hide() self.input.hide() format_ = QTextCharFormat() format_.setAnchor(True) self.output.textCursor().insertText('\n\n') if exitStatus == QProcess.NormalExit: format_.setForeground(Qt.green) self.output.textCursor().insertText( self.tr("Execution Successful!"), format_) else: format_.setForeground(Qt.red) self.output.textCursor().insertText( self.tr("Execution Interrupted"), format_) self.output.textCursor().insertText('\n\n') self.__post_execution() def insert_input(self): """Take the user input and send it to the process.""" text = self.input.text() + '\n' self._proc.writeData(text) self.output.textCursor().insertText(text, self.output.plain_format) self.input.setText("") def start_process(self, fileName, pythonPath=False, PYTHONPATH=None, programParams='', preExec='', postExec=''): """Prepare the output widget and start the process.""" self.lblInput.show() self.input.show() self.fileName = fileName self.pythonPath = pythonPath # FIXME, this is python interpreter self.programParams = programParams self.preExec = preExec self.postExec = postExec self.PYTHONPATH = PYTHONPATH self.__pre_execution() def __main_execution(self): """Execute the project.""" self.output.setCurrentCharFormat(self.output.plain_format) message = '' if self.__preScriptExecuted: self.__preScriptExecuted = False message = self.tr( "Pre Execution Script Successfully executed.\n\n") self.output.setPlainText(message + 'Running: %s (%s)\n\n' % (self.fileName, unicode(time.ctime()))) self.output.moveCursor(QTextCursor.Down) self.output.moveCursor(QTextCursor.Down) self.output.moveCursor(QTextCursor.Down) #runner.run_code_from_file(fileName) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH #change the working directory to the fileName dir file_directory = file_manager.get_folder(self.fileName) self._proc.setWorkingDirectory(file_directory) #force python to unbuffer stdin and stdout options = ['-u'] + settings.EXECUTION_OPTIONS.split() self.currentProcess = self._proc if self.PYTHONPATH: envpaths = [path for path in self.PYTHONPATH.splitlines()] env = QProcessEnvironment() system_environemnt = self._proc.systemEnvironment() for e in system_environemnt: key, value = unicode(e).split('=', 1) env.insert(key, value) for path in envpaths: env.insert('PYTHONPATH', path) self._proc.setProcessEnvironment(env) self._proc.start(self.pythonPath, options + [self.fileName] + [p.strip() for p in self.programParams.split(',') if p]) def __pre_execution(self): """Execute a script before executing the project.""" filePreExec = QFile(self.preExec) if filePreExec.exists() and \ bool(QFile.ExeUser & filePreExec.permissions()): ext = file_manager.get_file_extension(self.preExec) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH self.currentProcess = self._preExecScriptProc self.__preScriptExecuted = True if ext == 'py': self._preExecScriptProc.start(self.pythonPath, [self.preExec]) else: self._preExecScriptProc.start(self.preExec) else: self.__main_execution() def __post_execution(self): """Execute a script after executing the project.""" filePostExec = QFile(self.postExec) if filePostExec.exists() and \ bool(QFile.ExeUser & filePostExec.permissions()): ext = file_manager.get_file_extension(self.postExec) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH self.currentProcess = self._postExecScriptProc if ext == 'py': self._postExecScriptProc.start(self.pythonPath, [self.postExec]) else: self._postExecScriptProc.start(self.postExec) def __post_execution_message(self): """Print post execution message.""" self.output.textCursor().insertText('\n\n') format_ = QTextCharFormat() format_.setAnchor(True) format_.setForeground(Qt.green) self.output.textCursor().insertText( self.tr("Post Execution Script Successfully executed."), format_) def kill_process(self): """Kill the running process.""" self._proc.kill()
class RunWidget(QWidget): """Widget that show the execution output in the MiscContainer.""" 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 process_error(self, error): """Listen to the error signals from the running process.""" self.lblInput.hide() self.input.hide() self._proc.kill() format_ = QTextCharFormat() format_.setAnchor(True) format_.setForeground(Qt.red) if error == 0: self.output.textCursor().insertText(self.tr('Failed to start'), format_) else: self.output.textCursor().insertText( self.tr('Error during execution, QProcess error: %d' % error), format_) def finish_execution(self, exitCode, exitStatus): """Print a message and hide the input line when the execution ends.""" self.lblInput.hide() self.input.hide() format_ = QTextCharFormat() format_.setAnchor(True) self.output.textCursor().insertText('\n\n') if exitStatus == QProcess.NormalExit: format_.setForeground(Qt.green) self.output.textCursor().insertText( self.tr("Execution Successful!"), format_) else: format_.setForeground(Qt.red) self.output.textCursor().insertText( self.tr("Execution Interrupted"), format_) self.output.textCursor().insertText('\n\n') self.__post_execution() def insert_input(self): """Take the user input and send it to the process.""" text = self.input.text() + '\n' self._proc.writeData(text) self.output.textCursor().insertText(text, self.output.plain_format) self.input.setText("") def start_process(self, fileName, pythonPath=False, PYTHONPATH=None, programParams='', preExec='', postExec=''): """Prepare the output widget and start the process.""" self.lblInput.show() self.input.show() self.fileName = fileName self.pythonPath = pythonPath # FIXME, this is python interpreter self.programParams = programParams self.preExec = preExec self.postExec = postExec self.PYTHONPATH = PYTHONPATH self.__pre_execution() def __main_execution(self): """Execute the project.""" self.output.setCurrentCharFormat(self.output.plain_format) message = '' if self.__preScriptExecuted: self.__preScriptExecuted = False message = self.tr( "Pre Execution Script Successfully executed.\n\n") self.output.setPlainText(message + 'Running: %s (%s)\n\n' % (self.fileName, time.ctime())) self.output.moveCursor(QTextCursor.Down) self.output.moveCursor(QTextCursor.Down) self.output.moveCursor(QTextCursor.Down) #runner.run_code_from_file(fileName) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH #change the working directory to the fileName dir file_directory = file_manager.get_folder(self.fileName) self._proc.setWorkingDirectory(file_directory) #force python to unbuffer stdin and stdout options = ['-u'] + settings.EXECUTION_OPTIONS.split() self.currentProcess = self._proc if self.PYTHONPATH: envpaths = [path for path in self.PYTHONPATH.splitlines()] env = QProcessEnvironment() system_environemnt = self._proc.systemEnvironment() for e in system_environemnt: key, value = e.split('=', 1) env.insert(key, value) for path in envpaths: env.insert('PYTHONPATH', path) self._proc.setProcessEnvironment(env) self._proc.start(self.pythonPath, options + [self.fileName] + [p.strip() for p in self.programParams.split(',') if p]) def __pre_execution(self): """Execute a script before executing the project.""" filePreExec = QFile(self.preExec) if filePreExec.exists() and \ bool(QFile.ExeUser & filePreExec.permissions()): ext = file_manager.get_file_extension(self.preExec) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH self.currentProcess = self._preExecScriptProc self.__preScriptExecuted = True if ext == 'py': self._preExecScriptProc.start(self.pythonPath, [self.preExec]) else: self._preExecScriptProc.start(self.preExec) else: self.__main_execution() def __post_execution(self): """Execute a script after executing the project.""" filePostExec = QFile(self.postExec) if filePostExec.exists() and \ bool(QFile.ExeUser & filePostExec.permissions()): ext = file_manager.get_file_extension(self.postExec) if not self.pythonPath: self.pythonPath = settings.PYTHON_PATH self.currentProcess = self._postExecScriptProc if ext == 'py': self._postExecScriptProc.start(self.pythonPath, [self.postExec]) else: self._postExecScriptProc.start(self.postExec) def __post_execution_message(self): """Print post execution message.""" self.output.textCursor().insertText('\n\n') format_ = QTextCharFormat() format_.setAnchor(True) format_.setForeground(Qt.green) self.output.textCursor().insertText( self.tr("Post Execution Script Successfully executed."), format_) def kill_process(self): """Kill the running process.""" self._proc.kill()
class BatchFileSync(SyncProvider): 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 import_parser_module(self): import imp name = self.parser module = imp.find_module(name, [self.rootfolder]) module = imp.load_module(name, *module) self.parsermodule = module print self.parsermodule def start(self): if not self.parsermodule and self.parser: self.import_parser_module() self._output = "" self.haserror = False self.process.start(self.cmd, []) @property def output(self): return self._output @output.setter def output(self, value): self._output = value def error(self): self.haserror = True def complete(self, error, status): if error > 0 or self.haserror: stderr = self.process.readAllStandardError().data() self.syncError.emit(stderr) else: self.syncComplete.emit() self.syncFinished.emit() def readOutput(self): output = str(self.process.readAll()) ok = True if self.parsermodule: ok, output = self.parsermodule.sync_output(output) if not ok: self.haserror = True self.process.kill() self.syncError.emit(output) else: if output: self.syncMessage.emit(output)
class BatchFileSync(SyncProvider): 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 import_parser_module(self): import imp name = self.parser module = imp.find_module(name, [self.rootfolder]) module = imp.load_module(name, *module) self.parsermodule = module print self.parsermodule def start(self): if not self.parsermodule and self.parser: self.import_parser_module() self._output = "" self.haserror = False self.process.start(self.cmd, []) @property def output(self): return self._output @output.setter def output(self, value): self._output = value def error(self): self.haserror = True def complete(self, error, status): if error > 0 or self.haserror: stderr = self.process.readAllStandardError().data() self.syncError.emit(stderr) else: self.syncComplete.emit() self.syncFinished.emit() def readOutput(self): output = str(self.process.readAll()) ok = True if self.parsermodule: ok, output = self.parsermodule.sync_output(output) if not ok: self.haserror = True self.process.kill() self.syncError.emit(output) else: if output: self.syncMessage.emit(output)
class EjecutarWidget(QWidget): 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 _execution_finished(self, code, status): if status == QProcess.CrashExit: text = output_compiler.Item( self.tr("La ejecución se ha interrumpido")) text.setForeground(Qt.red) self.output.addItem(text) else: text = output_compiler.Item( self.tr("Ejecución Exitosa!")) text.setForeground(QColor("#7FE22A")) self.output.addItem(text) def run_compilation(self, sources): """ Se corre el comando gcc para la compilación """ # Ejecutable filename, files = sources if not files: # No es un proyecto files = [filename] path = QDir.fromNativeSeparators(filename) self.exe = os.path.splitext(os.path.basename(path))[0] # Generar el ejecutable en el directorio del código fuente exe_path = os.path.dirname(path) self.build_process.setWorkingDirectory(exe_path) # Se limpia el QListWidget self.output.clear() flags = settings.COMPILER_FLAGS.split() params = ['-o', self.exe] + flags gcc = 'gcc' if not sys.platform.startswith("linux"): gcc = os.path.join(self._environment, 'gcc') item = output_compiler.Item( self.tr(">>> Compilando: {0} ( en directorio {1} )").format( path.split('/')[-1], exe_path)) self.output.addItem(item) self.output.addItem(output_compiler.Item( self.tr(">>> Comando: {0}").format( gcc + ' ' + ' '.join(params) + ' ' + ' '.join(files)))) # Se inicia el proceso self.build_process.start(gcc, params + files) self.build_process.waitForFinished() def _compilation_finished(self, code, status): """ Cuando la compilación termina @codigoError toma dos valores: 0 = La compilación ha terminado de forma correcta 1 = La compilación ha fallado """ if status == QProcess.NormalExit and code == 0: self._compilation_failed = False item_ok = output_compiler.Item( self.tr("¡LA COMPILACIÓN HA SIDO EXITOSA!")) self.output.addItem(item_ok) item_ok.setForeground(QColor("#7FE22A")) else: self._compilation_failed = True item_error = output_compiler.Item( self.tr("¡LA COMPILACIÓN HA FALLADO!")) item_error.setForeground(QColor("#E20000")) self.output.addItem(item_error) syntax_ok = True if code == 0 else False self.emit(SIGNAL("updateSyntaxCheck(bool)"), syntax_ok) code_status = output_compiler.Item( self.tr("Proceso terminado con código: {0}").format(code), italic=True) self.output.addItem(code_status) count = self.output.count() self.output.setCurrentRow(count - 1, QItemSelectionModel.NoUpdate) def _compilation_error(self, error): """ Éste método se ejecuta cuando el inicio del proceso de compilación falla. Una de las causas puede ser la ausencia del compilador. """ text = output_compiler.Item( self.tr("Se ha producido un error. Compilador no encontrado.")) text.setForeground(Qt.red) self.output.addItem(text) def run_program(self, sources): """ Ejecuta el binario generado por el compilador """ path = os.path.dirname(sources[0]) self.execution_process.setWorkingDirectory(path) # Path ejecutable path_exe = os.path.join(path, self.exe) if not settings.IS_LINUX: path_exe += '.exe' # Si no existe se termina el proceso if not self._check_file_exists(path_exe): text = output_compiler.Item( self.tr("El archivo no existe: {0}").format(path_exe)) text.setForeground(Qt.red) self.output.addItem(text) return # Texto en la salida text = output_compiler.Item( self.tr("Ejecutando... {0}").format(path_exe)) self.output.addItem(text) if settings.IS_LINUX: # Run ! terminal = settings.get_setting('terminal') arguments = [os.path.join(paths.PATH, "tools", "run_script.sh %s" % path_exe)] self.execution_process.start(terminal, ['-e'] + arguments) else: pauser = os.path.join(paths.PATH, "tools", "pauser", "system_pause.exe") process = [pauser] + ["\"%s\"" % path_exe] Popen(process, creationflags=CREATE_NEW_CONSOLE) def _check_file_exists(self, exe): """ Comprueba si el ejecutable existe """ exists = True if not os.path.exists(exe): exists = False return exists @property def _environment(self): """ Devuelve la variable de entorno gcc """ return self._envgcc.value("PATH", "") def build_and_run(self, archivo): self.run_compilation(archivo) if not self._compilation_failed: self.run_program(archivo) def clean(self, exe): """ Elimina el binario generado por la compilación """ if exe is None: return binary = exe.split('.')[0] if not settings.IS_LINUX: binary += '.exe' os.remove(binary) def kill_process(self): """ Termina el proceso """ self.execution_process.kill()
class EjecutarWidget(QWidget): 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 _execution_finished(self, code, status): if status == QProcess.CrashExit: text = output_compiler.Item( self.tr("La ejecución se ha interrumpido")) text.setForeground(Qt.red) self.output.addItem(text) else: text = output_compiler.Item(self.tr("Ejecución Exitosa!")) text.setForeground(QColor("#7FE22A")) self.output.addItem(text) def run_compilation(self, sources): """ Se corre el comando gcc para la compilación """ # Ejecutable filename, files = sources if not files: # No es un proyecto files = [filename] path = QDir.fromNativeSeparators(filename) self.exe = os.path.splitext(os.path.basename(path))[0] # Generar el ejecutable en el directorio del código fuente exe_path = os.path.dirname(path) self.build_process.setWorkingDirectory(exe_path) # Se limpia el QListWidget self.output.clear() flags = settings.COMPILER_FLAGS.split() params = ['-o', self.exe] + flags gcc = 'gcc' if not sys.platform.startswith("linux"): gcc = os.path.join(self._environment, 'gcc') item = output_compiler.Item( self.tr(">>> Compilando: {0} ( en directorio {1} )").format( path.split('/')[-1], exe_path)) self.output.addItem(item) self.output.addItem( output_compiler.Item( self.tr(">>> Comando: {0}").format(gcc + ' ' + ' '.join(params) + ' ' + ' '.join(files)))) # Se inicia el proceso self.build_process.start(gcc, params + files) self.build_process.waitForFinished() def _compilation_finished(self, code, status): """ Cuando la compilación termina @codigoError toma dos valores: 0 = La compilación ha terminado de forma correcta 1 = La compilación ha fallado """ if status == QProcess.NormalExit and code == 0: self._compilation_failed = False item_ok = output_compiler.Item( self.tr("¡LA COMPILACIÓN HA SIDO EXITOSA!")) self.output.addItem(item_ok) item_ok.setForeground(QColor("#7FE22A")) else: self._compilation_failed = True item_error = output_compiler.Item( self.tr("¡LA COMPILACIÓN HA FALLADO!")) item_error.setForeground(QColor("#E20000")) self.output.addItem(item_error) syntax_ok = True if code == 0 else False self.emit(SIGNAL("updateSyntaxCheck(bool)"), syntax_ok) code_status = output_compiler.Item( self.tr("Proceso terminado con código: {0}").format(code), italic=True) self.output.addItem(code_status) count = self.output.count() self.output.setCurrentRow(count - 1, QItemSelectionModel.NoUpdate) def _compilation_error(self, error): """ Éste método se ejecuta cuando el inicio del proceso de compilación falla. Una de las causas puede ser la ausencia del compilador. """ text = output_compiler.Item( self.tr("Se ha producido un error. Compilador no encontrado.")) text.setForeground(Qt.red) self.output.addItem(text) def run_program(self, sources): """ Ejecuta el binario generado por el compilador """ path = os.path.dirname(sources[0]) self.execution_process.setWorkingDirectory(path) # Path ejecutable path_exe = os.path.join(path, self.exe) if not settings.IS_LINUX: path_exe += '.exe' # Si no existe se termina el proceso if not self._check_file_exists(path_exe): text = output_compiler.Item( self.tr("El archivo no existe: {0}").format(path_exe)) text.setForeground(Qt.red) self.output.addItem(text) return # Texto en la salida text = output_compiler.Item( self.tr("Ejecutando... {0}").format(path_exe)) self.output.addItem(text) if settings.IS_LINUX: # Run ! terminal = settings.get_setting('terminal') arguments = [ os.path.join(paths.PATH, "tools", "run_script.sh %s" % path_exe) ] self.execution_process.start(terminal, ['-e'] + arguments) else: pauser = os.path.join(paths.PATH, "tools", "pauser", "system_pause.exe") process = [pauser] + ["\"%s\"" % path_exe] Popen(process, creationflags=CREATE_NEW_CONSOLE) def _check_file_exists(self, exe): """ Comprueba si el ejecutable existe """ exists = True if not os.path.exists(exe): exists = False return exists @property def _environment(self): """ Devuelve la variable de entorno gcc """ return self._envgcc.value("PATH", "") def build_and_run(self, archivo): self.run_compilation(archivo) if not self._compilation_failed: self.run_program(archivo) def clean(self, exe): """ Elimina el binario generado por la compilación """ if exe is None: return binary = exe.split('.')[0] if not settings.IS_LINUX: binary += '.exe' os.remove(binary) def kill_process(self): """ Termina el proceso """ self.execution_process.kill()
class TerreImageProcess(): 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 run_process(self, command): logger.info(u"Running {}".format(command)) self.process.setProcessEnvironment(self.env) # logger.debug("..............{}".format(self.process.processEnvironment().value("OTB_APPLICATION_PATH"))) # logger.debug("..............{}".format(self.process.processEnvironment().value("PATH"))) # logger.debug("Environ : PATH {}".format(os.environ["PATH"])) # logger.debug("Environ : OTB_APPLICATION_PATH {}".format(os.environ.get("OTB_APPLICATION_PATH", "Empty"))) self.command = command self.process.start(command) if self.process.waitForStarted(): self.process.waitForFinished(-1) exit_code = self.process.exitCode() if exit_code != 0: self.error_management(exit_code) result = self.process.readAllStandardOutput() # logger.debug(" {} {}".format(type(result), result)) error = self.process.readAllStandardError().data() # logger.debug(repr(error)) if not error in ["\n", ""]: logger.error("error : %s"%(error)) output = result.data() logger.info(output) return result else: code_d_erreur = self.process.error() self.error_management(code_d_erreur) return None def error_management(self, errorCode): dic_err = { 0:"QProcess::FailedToStart", 1:"QProcess::Crashed", 2:"QProcess::TimedOut", 3:"QProcess::WriteError", 4:"QProcess::ReadError", 5:"QProcess::UnknownError", 127:"Other, The application may not have been found"} try: type_qt_error = dic_err[errorCode] logger.error(u"Error {} {}".format(errorCode, type_qt_error)) except KeyError: type_qt_error = "" error = self.process.readAllStandardError().data() logger.error(error) logger.error( self.process.readAllStandardOutput()) try: raise terre_image_exceptions.TerreImageRunProcessError(u"Error running : {}\n {}{}".format(self.command, type_qt_error, error )) except UnicodeError: raise terre_image_exceptions.TerreImageRunProcessError(u"Error running : {}\n {}".format(self.command, type_qt_error)) def set_env_var(self, varname, varval, append = False, pre = False): if append == True: if pre == False: # insert value at the end of the variable self.env.insert(varname, self.env.value(varname) + os.pathsep + varval) else: # insert value in head self.env.insert(varname, varval + os.pathsep + self.env.value(varname)) else: # replace value if existing self.env.insert(varname, varval) # logger.debug("env {} {}".format(varname, self.env.value(varname))) def set_otb_process_env(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.set_env_var("OTB_APPLICATION_PATH", os.path.join(dirname, "win32", "plugin"), pre=True) self.set_env_var("PATH", os.path.join(dirname, "win32", "bin"), append = False, pre=True) def set_otb_process_env_custom(self, otb_app_path="", path=""): """ Add the given values to OTB_APPLICATION_PATH and PATH environement variables Args: otb_app_path: path: Returns: """ self.set_env_var("OTB_APPLICATION_PATH", otb_app_path, pre=True) self.set_env_var("PATH", path, append = False, pre=True) def set_otb_process_env_default(self): """ Add the values from the config file to OTB_APPLICATION_PATH and PATH environement variables Args: otb_app_path: path: Returns: """ self.set_env_var("OTB_APPLICATION_PATH", terre_image_configuration.OTB_APPLICATION_PATH, pre=True) self.set_env_var("PATH", terre_image_configuration.PATH, append = True, pre=True) if terre_image_configuration.LD_LIBRARY_PATH: self.set_env_var("LD_LIBRARY_PATH", terre_image_configuration.LD_LIBRARY_PATH, append = True, pre=True)
class TerreImageProcess(): 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 run_process(self, command): logger.info(u"Running {}".format(command)) self.process.setProcessEnvironment(self.env) # logger.debug("..............{}".format(self.process.processEnvironment().value("OTB_APPLICATION_PATH"))) # logger.debug("..............{}".format(self.process.processEnvironment().value("PATH"))) # logger.debug("Environ : PATH {}".format(os.environ["PATH"])) # logger.debug("Environ : OTB_APPLICATION_PATH {}".format(os.environ.get("OTB_APPLICATION_PATH", "Empty"))) self.command = command self.process.start(command) if self.process.waitForStarted(): self.process.waitForFinished(-1) exit_code = self.process.exitCode() if exit_code != 0: self.error_management(exit_code) result = self.process.readAllStandardOutput() # logger.debug(" {} {}".format(type(result), result)) error = self.process.readAllStandardError().data() # logger.debug(repr(error)) if not error in ["\n", ""]: logger.error("error : %s" % (error)) output = result.data() logger.info(output) return result else: code_d_erreur = self.process.error() self.error_management(code_d_erreur) return None def error_management(self, errorCode): dic_err = { 0: "QProcess::FailedToStart", 1: "QProcess::Crashed", 2: "QProcess::TimedOut", 3: "QProcess::WriteError", 4: "QProcess::ReadError", 5: "QProcess::UnknownError", 127: "Other, The application may not have been found" } try: type_qt_error = dic_err[errorCode] logger.error(u"Error {} {}".format(errorCode, type_qt_error)) except KeyError: type_qt_error = "" error = self.process.readAllStandardError().data() logger.error(error) logger.error(self.process.readAllStandardOutput()) try: raise terre_image_exceptions.TerreImageRunProcessError( u"Error running : {}\n {}{}".format(self.command, type_qt_error, error)) except UnicodeError: raise terre_image_exceptions.TerreImageRunProcessError( u"Error running : {}\n {}".format(self.command, type_qt_error)) def set_env_var(self, varname, varval, append=False, pre=False): if append == True: if pre == False: # insert value at the end of the variable self.env.insert(varname, self.env.value(varname) + os.pathsep + varval) else: # insert value in head self.env.insert(varname, varval + os.pathsep + self.env.value(varname)) else: # replace value if existing self.env.insert(varname, varval) # logger.debug("env {} {}".format(varname, self.env.value(varname))) def set_otb_process_env(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.set_env_var("OTB_APPLICATION_PATH", os.path.join(dirname, "win32", "plugin"), pre=True) self.set_env_var("PATH", os.path.join(dirname, "win32", "bin"), append=False, pre=True) def set_otb_process_env_custom(self, otb_app_path="", path=""): """ Add the given values to OTB_APPLICATION_PATH and PATH environement variables Args: otb_app_path: path: Returns: """ self.set_env_var("OTB_APPLICATION_PATH", otb_app_path, pre=True) self.set_env_var("PATH", path, append=False, pre=True) def set_otb_process_env_default(self): """ Add the values from the config file to OTB_APPLICATION_PATH and PATH environement variables Args: otb_app_path: path: Returns: """ self.set_env_var("OTB_APPLICATION_PATH", terre_image_configuration.OTB_APPLICATION_PATH, pre=True) self.set_env_var("PATH", terre_image_configuration.PATH, append=True, pre=True) if terre_image_configuration.LD_LIBRARY_PATH: self.set_env_var("LD_LIBRARY_PATH", terre_image_configuration.LD_LIBRARY_PATH, append=True, pre=True)