def __init__(self): super(MainWindow, self).__init__() self.line_edit = None # Procesos self.build_process = QProcess(self) if not sys.platform.startswith('linux'): self._envgcc = QProcessEnvironment.systemEnvironment() self._envgcc.insert("QT5DIR", "/home/epson/Qt/5.8/gcc_64") self._envgcc.insert("QT_QPA_PLATFORM_PLUGIN_PATH", "/home/epson/Qt/5.8/gcc_64/plugins/platforms") self._envgcc.insert("QT_PLUGIN_PATH", "/home/epson/Qt/5.8/gcc_64/plugins") self._envgcc.insert("QML_IMPORT_PATH", "/home/epson/Qt/5.8/gcc_64/qml") self._envgcc.insert("QML2_IMPORT_PATH", "/home/epson/Qt/5.8/gcc_64/qml") self._envgcc.insert( "QT_VIRTUALKEYBOARD_LAYOUT_PATH", "/home/epson/INTERACT/interact-ii/basic-b2qt.qml") self._envgcc.insert( "QT_VIRTUALKEYBOARD_STYLE", "/home/epson/INTERACT/interact-ii/basic-b2qt.qml") self._envgcc.insert("QT_IM_MODULE", "qtvirtualkeyboard") self.build_process.setProcessEnvironment(self._envgcc) self.execution_process = QProcess(self) self.init_ui()
def init_broker(self): rs_debug("init_broker") modname = self.input.text() if modname == "": modname = self.handle_name_aliasing() self.input.setText(modname) cmdline = "\"%s\" -u \"%s\" --idb \"%s\"" % (PYTHON_PATH, BROKER_PATH, modname) rs_log("cmdline: %s" % cmdline) self.broker = Broker(self.parser) env = QProcessEnvironment.systemEnvironment() env.insert("IDB_PATH", IDB_PATH) env.insert("PYTHON_PATH", PYTHON_PATH) try: self.broker.started.connect(self.cb_broker_started) self.broker.finished.connect(self.cb_broker_finished) self.broker.setProcessEnvironment(env) self.broker.start(cmdline) except Exception as e: rs_log("[-] failed to start broker: %s\n%s" % (str(e), traceback.format_exc())) return self.init_hotkeys() self.broker.worker.name = modname
def _runFile(self, file): """子进程运行文件 :param file: 文件 """ file = os.path.abspath(file) process = QProcess(self) process.setProperty('file', file) process.readChannelFinished.connect(self.onReadChannelFinished) env = QProcessEnvironment.systemEnvironment() # libpath = get_python_lib() # env.insert('QT_QPA_PLATFORM_PLUGIN_PATH', os.path.join( # libpath, 'PyQt5', 'Qt', 'plugins', 'platforms')) # env.insert('QT_QPA_PLATFORM_PLUGIN_PATH', # os.path.abspath('platforms')) env.insert('QML_IMPORT_PATH', os.path.abspath('qml')) env.insert('QML2_IMPORT_PATH', env.value('QML_IMPORT_PATH')) if os.name == 'nt': env.insert( 'PATH', QLibraryInfo.location(QLibraryInfo.BinariesPath) + os.pathsep + env.value('PATH')) env.insert( 'PATH', os.path.dirname(os.path.abspath(sys.argv[0])) + os.pathsep + env.value('PATH')) process.setProcessEnvironment(env) # if sys.executable.endswith('python.exe'): process.setWorkingDirectory(os.path.dirname(file)) process.start(sys.executable, [file])
def tribler_api(api_port, tmpdir_factory): # Run real Core and record responses core_env = QProcessEnvironment.systemEnvironment() core_env.insert("CORE_BASE_PATH", str(RUN_TRIBLER_PY.parent / "tribler-core")) core_env.insert("CORE_PROCESS", "1") core_env.insert("CORE_API_PORT", f"{api_port}") core_env.insert("CORE_API_KEY", "") core_env.insert("TRIBLER_CORE_TEST_MODE", "1") temp_state_dir = tmpdir_factory.mktemp('tribler_state_dir') core_env.insert("TSTATEDIR", str(temp_state_dir)) core_process = QProcess() def on_core_read_ready(): raw_output = bytes(core_process.readAll()) decoded_output = raw_output.decode(errors="replace") print(decoded_output.strip()) # noqa: T001 core_process.setProcessEnvironment(core_env) core_process.setReadChannel(QProcess.StandardOutput) core_process.setProcessChannelMode(QProcess.MergedChannels) connect(core_process.readyRead, on_core_read_ready) core_process.start("python3", [str(RUN_TRIBLER_PY.absolute())]) yield core_process core_process.kill() core_process.waitForFinished()
def main(): if sys.version_info < (3, 5): raise RuntimeError('This package requires Python 3.5 or later') site_packages = get_python_lib() print('site_packages', site_packages) current_dir = os.path.dirname(os.path.abspath(sys.argv[0])) print('current_dir', current_dir) env = QProcessEnvironment.systemEnvironment() PATH = '{0};{1};{2}'.format(os.path.dirname(PyQt5.__file__), sys.prefix, env.value('PATH', '')) env.insert('PATH', PATH) env.insert('PYQTDESIGNERPATH', os.path.join(current_dir, 'Plugins')) env.insert('PYTHONPATH', os.path.join(current_dir)) print('PATH', env.value('PATH', '')) print('PYQTDESIGNERPATH', env.value('PYQTDESIGNERPATH', '')) print('PYTHONPATH', env.value('PYTHONPATH', '')) ext = '.exe' if os.name == 'nt' else '' designer = QProcess() designer.setProcessEnvironment(env) # for PyQt5.5 latter,pyqt5-tools maybe have problem designer_bin = QLibraryInfo.location( QLibraryInfo.BinariesPath) + os.sep + 'designer' + ext print('designer_bin', designer_bin) if os.path.exists(designer_bin): designer.start(designer_bin) designer.waitForFinished(-1) sys.exit(designer.exitCode()) else: raise Exception('Can not find designer')
def _debug(self): if self.editor.isModified(): self._slot_save() self.console.clear() self.editor.setReadOnly(True) qenv = QProcessEnvironment.systemEnvironment() qenv.insert('PYTHONPATH', PATH) self.__proc.setProcessEnvironment(qenv) self.__proc.setWorkingDirectory( os.path.dirname(os.path.realpath(self.__filename))) self.__proc.start(sys.executable + ' -u -m jsonpdb "' + self.__filename + '" ' + self.line_edit_args.text()) # set breakpoints (for current file and others) for row in range(self.listWidgetBreakpoints.count()): list_item = self.listWidgetBreakpoints.item(row) lineno = list_item.data(Qt.UserRole + 1) self.__proc.write(('b ' + self.__filename + ':' + str(lineno + 1) + '\n').encode(PROC_ENCODING)) for filename, linenos in self.__saved_breakpoints.items(): if filename == self.__filename: continue for lineno in linenos: self.__proc.write(('b ' + filename + ':' + str(lineno + 1) + '\n').encode(PROC_ENCODING)) self.__dbg_running = True self._update_ui() self._update_vars_and_stack()
def __init__(self, outputTextEdit, v2rayPath="v2ray", v2rayOption="", bridgetreasureChest=False): super().__init__() self.outputTextEdit = outputTextEdit self.v2rayPath = v2rayPath self.v2rayOption = v2rayOption self.bridgetreasureChest = bridgetreasureChest if not self.bridgetreasureChest: from bridgehouse.extension import bridgetreasureChest self.bridgetreasureChest = bridgetreasureChest.bridgetreasureChest( ) self.v2rayProcess = QProcess() self.v2rayProcess.setProcessChannelMode(QProcess.MergedChannels) self.v2rayProcess.setProcessEnvironment( QProcessEnvironment.systemEnvironment()) self.v2rayProcess.readyRead.connect(self.setoutputTextEdit) self.v2rayProcess.started.connect(self.oncreatePIDFile) self.start.connect(self.onstart) self.stop.connect(self.onstop) self.translate = QCoreApplication.translate self.pidFile = ".v2rayPID"
def __init__(self, what, *, verbose=False, additional_env=None, output_messages=False, parent=None): super().__init__(parent) self._what = what self.verbose = verbose self._output_messages = output_messages self._started = False self.cmd = None self.args = None self._proc = QProcess(self) self._proc.errorOccurred.connect(self._on_error) self._proc.errorOccurred.connect(self.error) self._proc.finished.connect(self._on_finished) self._proc.finished.connect(self.finished) self._proc.started.connect(self._on_started) self._proc.started.connect(self.started) if additional_env is not None: procenv = QProcessEnvironment.systemEnvironment() for k, v in additional_env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv)
def __init__(self, vcs, parent=None): """ Constructor @param vcs reference to the vcs object @param parent parent widget (QWidget) """ super(SvnPropListDialog, self).__init__(parent) self.setupUi(self) self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True) self.process = QProcess() env = QProcessEnvironment.systemEnvironment() env.insert("LANG", "C") self.process.setProcessEnvironment(env) self.vcs = vcs self.propsList.headerItem().setText(self.propsList.columnCount(), "") self.propsList.header().setSortIndicator(0, Qt.AscendingOrder) self.process.finished.connect(self.__procFinished) self.process.readyReadStandardOutput.connect(self.__readStdout) self.process.readyReadStandardError.connect(self.__readStderr) self.rx_path = QRegExp(r"Properties on '([^']+)':\s*") self.rx_prop = QRegExp(r" (.*) *: *(.*)[\r\n]") self.lastPath = None self.lastProp = None self.propBuffer = ""
def init_broker(self): print "[*] init_broker" modname = self.input.text().encode('ascii', 'replace') cmdline = u"\"%s\" -u \"%s\" --idb \"%s\"" % ( os.path.join(PYTHON_PATH, PYTHON_BIN), BROKER_PATH, modname) print "[*] init broker,", cmdline self.broker = Broker(self.parser) env = QProcessEnvironment.systemEnvironment() env.insert("IDB_PATH", IDB_PATH) env.insert("PYTHON_PATH", os.path.realpath(PYTHON_PATH)) env.insert("PYTHON_BIN", PYTHON_BIN) try: self.broker.started.connect(self.cb_broker_started) self.broker.finished.connect(self.cb_broker_finished) self.broker.setProcessEnvironment(env) self.broker.start(cmdline) except Exception as e: print "[-] failed to start broker: %s\n%s" % (str(e), traceback.format_exc()) return self.init_hotkeys() self.broker.worker.name = modname
def okButtonClicked(self): print("OK button clicked") p = QProcess() env = QProcessEnvironment.systemEnvironment() env.insert("SUDO_ASKPASS", os.path.dirname(__file__) + "/askpass.py") # FIXME: This is not working p.setProcessEnvironment(env) p.setProgram("sudo") p.setArguments(["-A", "-E", os.path.dirname(__file__) + "/adduser.sh", self.username.text(), self.password.text()]) p.start() p.waitForFinished() err = p.readAllStandardError().data().decode() err = err.replace("QKqueueFileSystemWatcherEngine::addPaths: open: No such file or directory", "").strip() # FIXME: Where is this coming from, remove it at the root of the problem if err and err != "": print(err) msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText(err) # msg.setInformativeText('More information') msg.setWindowTitle("Error") msg.exec_() out = p.readAllStandardOutput().data().decode() if out: print(out) if "Successfully added" in out: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Successfully added the user.") # msg.setInformativeText('More information') msg.setWindowTitle(" ") msg.exec_() self.close() print("p.exitStatus():", p.exitStatus()) if p.exitStatus() != 0: print("An error occured; TODO: Handle it in the GUI")
def _start_process(self, script_name, terminal_title, *args): if not self.daemon_manager.is_local or CommandLineArgs.under_nsm: # utility scripts are not available if daemon is not # on the same machine, or if current session is a subsession return if self._process.state(): QMessageBox.critical( self.main_win, _translate('utilities', 'Other script running'), _translate( 'utilities', "An utility script is already running,\n" "please close its terminal and start again !")) return process_env = QProcessEnvironment.systemEnvironment() process_env.insert('RAY_CONTROL_PORT', str(self.daemon_manager.get_port())) self._process.setProcessEnvironment(process_env) terminal_args = self._which_terminal(terminal_title) if not terminal_args: return full_script_path = os.path.join(self._get_scripts_path(), script_name) terminal = terminal_args.pop(0) self._process.setProgram(terminal) self._process.setArguments( terminal_args + ["utility_script_keeper.sh", full_script_path] + list(args)) self._process.start()
def init_broker(self): print "[*] init_broker" modname = self.input.text().encode('ascii', 'replace') cmdline = u"\"%s\" -u \"%s\" --idb \"%s\"" % (os.path.join( PYTHON_PATH, PYTHON_BIN), BROKER_PATH, modname) print "[*] init broker,", cmdline self.broker = Broker(self.parser) env = QProcessEnvironment.systemEnvironment() env.insert("IDB_PATH", IDB_PATH) env.insert("PYTHON_PATH", os.path.realpath(PYTHON_PATH)) env.insert("PYTHON_BIN", PYTHON_BIN) try: self.broker.started.connect(self.cb_broker_started) self.broker.finished.connect(self.cb_broker_finished) self.broker.setProcessEnvironment(env) self.broker.start(cmdline) except Exception as e: print "[-] failed to start broker: %s\n%s" % ( str(e), traceback.format_exc()) return self.init_hotkeys() self.broker.worker.name = modname
def initProc(self) -> None: self.proc = QProcess(self.parent) self.proc.setProcessChannelMode(QProcess.MergedChannels) env = QProcessEnvironment.systemEnvironment() self.proc.setProcessEnvironment(env) self.proc.setWorkingDirectory(self.getAppPath()) if hasattr(self.proc, 'errorOccurred'): self.proc.errorOccurred.connect(self.cmdError)
def __init__(self): super().__init__() # # Always run unbuffered and with UTF-8 IO encoding # self.environment = QProcessEnvironment.systemEnvironment() self.environment.insert("PYTHONUNBUFFERED", "1") self.environment.insert("PYTHONIOENCODING", "utf-8")
def startProcess(self, args, workingDir=None, setLanguage=False): """ Public slot used to start the process. @param args list of arguments for the process (list of strings) @param workingDir working directory for the process (string) @param setLanguage flag indicating to set the language to "C" (boolean) @return flag indicating a successful start of the process """ self.errorGroup.hide() self.normal = False self.intercept = False self.__hasAddOrDelete = False self.proc = QProcess() if setLanguage: env = QProcessEnvironment.systemEnvironment() env.insert("LANG", "C") self.proc.setProcessEnvironment(env) nargs = [] lastWasPwd = False for arg in args: if lastWasPwd: lastWasPwd = True continue nargs.append(arg) if arg == '--password': lastWasPwd = True nargs.append('*****') self.resultbox.append(' '.join(nargs)) self.resultbox.append('') self.proc.finished.connect(self.__procFinished) self.proc.readyReadStandardOutput.connect(self.__readStdout) self.proc.readyReadStandardError.connect(self.__readStderr) if workingDir: self.proc.setWorkingDirectory(workingDir) self.proc.start('svn', args) procStarted = self.proc.waitForStarted(5000) if not procStarted: self.buttonBox.setFocus() self.inputGroup.setEnabled(False) self.inputGroup.hide() E5MessageBox.critical( self, self.tr('Process Generation Error'), self.tr( 'The process {0} could not be started. ' 'Ensure, that it is in the search path.' ).format('svn')) else: self.inputGroup.setEnabled(True) self.inputGroup.show() return procStarted
def getQProcess(snap_controller): '''initialize a QProcess with the correct environment and output-files''' proc = QProcess() proc.setWorkingDirectory(snap_controller.lastOutputDir) proc.setStandardOutputFile(os.path.join(snap_controller.lastOutputDir,"snap.log.out"), QIODevice.Append) proc.setStandardErrorFile(os.path.join(snap_controller.lastOutputDir,"snap.log.out"), QIODevice.Append) env = QProcessEnvironment.systemEnvironment() env.insert("OMP_NUM_THREADS", "1") proc.setProcessEnvironment(env) return proc
def initProc(program: str=None, finish: pyqtSlot=None, workingdir: str=None) -> QProcess: p = QProcess() p.setProcessEnvironment(QProcessEnvironment.systemEnvironment()) p.setProcessChannelMode(QProcess.MergedChannels) if workingdir is not None: p.setWorkingDirectory(workingdir) if program is not None: p.setProgram(program) if finish is not None: p.finished.connect(finish) return p
def get_app_config_path(self) -> str: if self.flatpak: confpath = QProcessEnvironment.systemEnvironment().value( 'XDG_CONFIG_HOME', '') if len(confpath): return confpath else: return os.path.join(QDir.homePath(), '.var', 'app', vidcutter.__desktopid__, 'config') return QStandardPaths.writableLocation( QStandardPaths.AppConfigLocation).replace( qApp.applicationName(), qApp.applicationName().lower())
def start_cura(): global cura_process cura_process = QProcess() env = QProcessEnvironment.systemEnvironment() env.insert("PYTHONPATH", "/home/ahiemstra/dev/master/inst/lib/python3/dist-packages/") cura_process.setProcessEnvironment(env) cura_process.start("/usr/bin/python", ["/home/ahiemstra/dev/master/inst/bin/cura"]) cura_process.waitForStarted() time.sleep(30)
def launchQml(self, name): import_path = self.resolveDataDir(name) qml = self.resolveQmlFile(name) process = QProcess(self) process.error.connect(self.launchError) env = QProcessEnvironment.systemEnvironment() env.insert('QML2_IMPORT_PATH', import_path) process.setProcessEnvironment(env) executable = QLibraryInfo.location(QLibraryInfo.BinariesPath) + '/qmlscene' Colors.debug("Launching:", executable) process.start(executable, [qml])
def prepareProcess(proc, language=""): """ Public function to prepare the given process. @param proc reference to the process to be prepared (QProcess) @param language language to be set (string) """ env = QProcessEnvironment.systemEnvironment() # set the language for the process if language: env.insert("LANGUAGE", language) proc.setProcessEnvironment(env)
def open_app(self, instance, path, args, vproject): current_state = instance.state() if current_state == QProcess.NotRunning: env = QProcessEnvironment.systemEnvironment() env.insert('VPROJECT', vproject) instance.setProcessEnvironment(env) instance.start('"{}"'.format(path), args) instance.waitForStarted() else: show_dialog( title='Instance Already Running', text='A instance of that app is already running!', icon='Information', parent=self, )
def exec_(self): self.p = QProcess() self.p.setProcessChannelMode(QProcess.MergedChannels) self.p.readyReadStandardOutput.connect(self.onStdOut) self.p.error.connect(self.onError) self.p.finished.connect(self.onFinished) self.textWidget.clear() self.closeBtn.hide() self.killed = False self.killBtn.show() self.killBtn.setFocus() self.show() env = QProcessEnvironment.systemEnvironment() env.remove("TERM") self.p.setProcessEnvironment(env) super(RunSCHISMDialog, self).exec_()
def _run(self): # auto-save? if self.editor.isModified(): self._slot_save() self.console.clear() self.editor.setReadOnly(True) qenv = QProcessEnvironment.systemEnvironment() qenv.insert('PYTHONPATH', PATH) self.__proc.setProcessEnvironment(qenv) self.__proc.setWorkingDirectory( os.path.dirname(os.path.realpath(self.__filename))) self.__proc.start(sys.executable + ' "' + self.__filename + '" ' + self.line_edit_args.text()) self.__running = True self._update_ui()
def _start(self, args, env): """Actually start the process.""" executable, exec_args = self._executable_args() if args is None: args = self._default_args() procenv = QProcessEnvironment.systemEnvironment() if env is not None: for k, v in env.items(): procenv.insert(k, v) self.proc.readyRead.connect(self.read_log) self.proc.setProcessEnvironment(procenv) self.proc.start(executable, exec_args + args) ok = self.proc.waitForStarted() assert ok assert self.is_running()
def start_process(self, workspace, script): """ Start the child process from the workspace with the script. """ self.script = os.path.abspath(os.path.normcase(script)) logger.info('Running script: {}'.format(script)) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.MergedChannels) # Force buffers to flush immediately. env = QProcessEnvironment.systemEnvironment() env.insert('PYTHONUNBUFFERED', '1') self.process.setProcessEnvironment(env) logger.info('Working directory: {}'.format(workspace)) self.process.setWorkingDirectory(workspace) self.process.readyRead.connect(self.read) self.process.finished.connect(self.finished) self.process.start('mu-debug', [self.script])
def start(self, command, src_addr=None, previous_slot=(None, '')): if self.isRunning(): return False command_string = '' if command == ray.Command.START: command_string = 'start' elif command == ray.Command.SAVE: command_string = 'save' elif command == ray.Command.STOP: command_string = 'stop' else: return False scripts_dir = "%s/%s.%s" % \ (self.client.session.path, ray.SCRIPTS_DIR, self.client.client_id) script_path = "%s/%s.sh" % (scripts_dir, command_string) if not os.access(script_path, os.X_OK): return False self._pending_command = command if src_addr: # Remember the caller of the function calling the script # Then, when script is finished # We could reply to this (address, path) self._initial_caller = previous_slot self.src_addr = src_addr process_env = QProcessEnvironment.systemEnvironment() process_env.insert('RAY_CONTROL_PORT', str(self.getServerPort())) process_env.insert('RAY_CLIENT_SCRIPTS_DIR', scripts_dir) process_env.insert('RAY_CLIENT_ID', self.client.client_id) process_env.insert('RAY_CLIENT_EXECUTABLE', self.client.executable_path) process_env.insert('RAY_CLIENT_ARGUMENTS', self.client.arguments) self._process.setProcessEnvironment(process_env) self.client.sendGuiMessage( _translate('GUIMSG', '--- Custom script %s started...%s') % (ray.highlightText(script_path), self.client.client_id)) self._process.start(script_path, []) return True
def _run_process(self, cmd, *args, env): """Start the given command via QProcess. Args: cmd: The command to be started. *args: The arguments to hand to the command env: A dictionary of environment variables to add. """ self._proc = QProcess(self) procenv = QProcessEnvironment.systemEnvironment() procenv.insert('QUTE_FIFO', self._filepath) if env is not None: for k, v in env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv) self._proc.error.connect(self.on_proc_error) self._proc.finished.connect(self.on_proc_finished) self._proc.start(cmd, args)
def __init__(self): super(ProcessExecutor, self).__init__() self._env = QProcessEnvironment.systemEnvironment() self._origCmd = None self._finalExe = None self._finalArgs = [] self._hostname = 'localhost' self._localHost = socket.gethostname() self._process = QProcess() self._detached = False self._withX11 = False self._workingDir = None self._process.started.connect(self.started.emit) self._process.finished.connect(self.finished.emit) self._process.readyReadStandardOutput.connect(self._onNewStdOut) self._process.readyReadStandardError.connect(self._onNewStdErr)
def __init__( self, what: str, *, verbose: bool = False, additional_env: Mapping[str, str] = None, output_messages: bool = False, parent: QObject = None, ): super().__init__(parent) self.what = what self.verbose = verbose self._output_messages = output_messages self.outcome = ProcessOutcome(what=what) self.cmd: Optional[str] = None self.resolved_cmd: Optional[str] = None self.args: Optional[Sequence[str]] = None self.pid: Optional[int] = None self.stdout: str = "" self.stderr: str = "" self._cleanup_timer = usertypes.Timer(self, 'process-cleanup') self._cleanup_timer.setTimerType(Qt.VeryCoarseTimer) self._cleanup_timer.setInterval(3600 * 1000) # 1h self._cleanup_timer.timeout.connect(self._on_cleanup_timer) self._cleanup_timer.setSingleShot(True) self._proc = QProcess(self) self._proc.errorOccurred.connect(self._on_error) self._proc.errorOccurred.connect(self.error) self._proc.finished.connect(self._on_finished) self._proc.finished.connect(self.finished) self._proc.started.connect(self._on_started) self._proc.started.connect(self.started) self._proc.readyReadStandardOutput.connect(self._on_ready_read_stdout) self._proc.readyReadStandardError.connect(self._on_ready_read_stderr) if additional_env is not None: procenv = QProcessEnvironment.systemEnvironment() for k, v in additional_env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv)
def getSettingsPath() -> str: if sys.platform == 'win32': settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', 'vidcutter') elif sys.platform == 'darwin': settings_path = os.path.join(QDir.homePath(), 'Library', 'Preferences', 'vidcutter') else: if QFileInfo(__file__).absolutePath().startswith('/app/'): settings_path = QProcessEnvironment.systemEnvironment().value( 'XDG_CONFIG_HOME', '') if not len(settings_path): settings_path = os.path.join(QDir.homePath(), '.var', 'app', vidcutter.__desktopid__, 'config') else: settings_path = os.path.join(QDir.homePath(), '.config', 'vidcutter') return os.path.join(settings_path, 'vidcutter.ini')
def prepareProcess(proc, encoding="", language=""): """ Public function to prepare the given process. @param proc reference to the proces to be prepared (QProcess) @param encoding encoding to be used by the process (string) @param language language to be set (string) """ env = QProcessEnvironment.systemEnvironment() env.insert("HGPLAIN", '1') # set the encoding for the process if encoding: env.insert("HGENCODING", encoding) # set the language for the process if language: env.insert("LANGUAGE", language) proc.setProcessEnvironment(env)
def qtDesignerStart(): """ Set widgets/plugins paths and start QtDesigner """ # Get base path and QProcess system environment base = os.path.dirname(__file__) env = QProcessEnvironment.systemEnvironment() # Path for tell python where it can find the widgets directory pybase = os.path.join(base, 'python') # Path for tell QtDesigner where it can find the plugins directory wbase = os.path.join(base, 'widgets') # Insert paths to QProcess system environment env.insert('PYQTDESIGNERPATH', pybase) env.insert('PYTHONPATH', wbase) # inform user inform('env add "PYQTDESIGNERPATH" plugins path - ' + pybase) inform('env add "PYTHONPATH" widgets path - ' + wbase) # Create QProcess and set environment designer = QProcess() designer.setProcessEnvironment(env) # Get QtDesigner binaries path designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath) # Platform specefic if sys.platform == 'darwin': designer_bin += '/Designer.app/Contents/MacOS/Designer' else: designer_bin += '/designer' # inform user inform('designer bin - ' + designer_bin) inform('start QtDesigner...') # Start QtDesigner designer.start(designer_bin) designer.waitForFinished(-1) sys.exit(designer.exitCode())
def __init__(self, what, *, verbose=False, additional_env=None, parent=None): super().__init__(parent) self._what = what self.verbose = verbose self._started = False self.cmd = None self.args = None self._proc = QProcess(self) self._proc.error.connect(self.on_error) self._proc.error.connect(self.error) self._proc.finished.connect(self.on_finished) self._proc.finished.connect(self.finished) self._proc.started.connect(self.on_started) self._proc.started.connect(self.started) if additional_env is not None: procenv = QProcessEnvironment.systemEnvironment() for k, v in additional_env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv)
def launchExample(self, name): executable = self.resolveExeFile(name) process = QProcess(self) process.error.connect(self.launchError) if sys.platform == 'win32': # Make sure it finds the DLLs on Windows. env = QProcessEnvironment.systemEnvironment() env.insert('PATH', QLibraryInfo.location(QLibraryInfo.BinariesPath) + ';' + env.value('PATH')) process.setProcessEnvironment(env) if self.info[name]['changedirectory'] != 'false': workingDirectory = self.resolveDataDir(name) process.setWorkingDirectory(workingDirectory) Colors.debug("Setting working directory:", workingDirectory) Colors.debug("Launching:", executable) process.start(sys.executable, [executable])
def flashDataPathForOS(): """ Function to determine the OS dependent path where Flash cookies are stored. @return Flash data path @rtype str """ # On Microsoft Windows NT 5.x and 6.x, they are stored in: # %APPDATA%\Macromedia\Flash Player\#SharedObjects\ # %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys\ # On Mac OS X, they are stored in: # ~/Library/Preferences/Macromedia/Flash Player/#SharedObjects/ # ~/Library/Preferences/Macromedia/Flash Player/macromedia.com/support/⏎ # flashplayer/sys/ # On Linux or Unix, they are stored in: # ~/.macromedia/Flash_Player/#SharedObjects/ # ~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/ # For Linux and Unix systems, if the open-source Gnash plugin is being used # instead of the official Adobe Flash, they will instead be found at: # ~/.gnash/SharedObjects/ flashPath = "" if Globals.isWindowsPlatform(): appData = QProcessEnvironment.systemEnvironment().value("APPDATA") appData = appData.replace("\\", "/") flashPath = appData + "/Macromedia/Flash Player" elif Globals.isMacPlatform(): flashPath = os.path.expanduser( "~/Library/Preferences/Macromedia/Flash Player") else: if os.path.exists(os.path.expanduser("~/.macromedia")): flashPath = os.path.expanduser("~/.macromedia/Flash_Player") elif os.path.exists(os.path.expanduser("~/.gnash")): flashPath = os.path.expanduser("~/.gnash") return flashPath
def _start(self, args, env): """Actually start the process.""" executable, exec_args = self._executable_args() if args is None: args = self._default_args() if env is None: procenv = QProcessEnvironment.systemEnvironment() else: procenv = QProcessEnvironment() for k, v in env.items(): procenv.insert(k, v) passthrough_vars = ['DISPLAY', 'HOME'] # so --no-xvfb works for var in passthrough_vars: if var in os.environ: procenv.insert(var, os.environ[var]) self.proc.readyRead.connect(self.read_log) self.proc.setProcessEnvironment(procenv) self.proc.start(executable, exec_args + args) ok = self.proc.waitForStarted() assert ok assert self.is_running()
def start_process(self, script_name, working_directory, interactive=True, debugger=False, command_args=None, envars=None, runner=None, python_args=None): """ Start the child Python process. Will run the referenced Python script_name within the context of the working directory. If interactive is True (the default) the Python process will run in interactive mode (dropping the user into the REPL when the script completes). If debugger is True (the default is False) then the script will run within a debug runner session. If there is a list of command_args (the default is None), then these will be passed as further arguments into the script to be run. If there is a list of environment variables, these will be part of the context of the new child process. If runner is given, this is used as the command to start the Python process. If python_args is given, these are passed as arguments to the Python runtime used to launch the child process. """ self.script = os.path.abspath(os.path.normcase(script_name)) logger.info('Running script: {}'.format(self.script)) if interactive: logger.info('Running with interactive mode.') if command_args is None: command_args = [] logger.info('Command args: {}'.format(command_args)) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.MergedChannels) # Force buffers to flush immediately. env = QProcessEnvironment.systemEnvironment() env.insert('PYTHONUNBUFFERED', '1') env.insert('PYTHONIOENCODING', 'utf-8') if sys.platform == 'darwin': parent_dir = os.path.dirname(__file__) if '.app/Contents/Resources/app/mu' in parent_dir: # Mu is running as a macOS app bundle. Ensure the expected # paths are in PYTHONPATH of the subprocess. env.insert('PYTHONPATH', ':'.join(sys.path)) if envars: logger.info('Running with environment variables: ' '{}'.format(envars)) for name, value in envars: env.insert(name, value) logger.info('Working directory: {}'.format(working_directory)) self.process.setWorkingDirectory(working_directory) self.process.setProcessEnvironment(env) self.process.readyRead.connect(self.read_from_stdout) self.process.finished.connect(self.finished) logger.info('Python path: {}'.format(sys.path)) if debugger: # Start the mu-debug runner for the script. parent_dir = os.path.join(os.path.dirname(__file__), '..') mu_dir = os.path.abspath(parent_dir) runner = os.path.join(mu_dir, 'mu-debug.py') python_exec = sys.executable args = [runner, self.script, ] + command_args self.process.start(python_exec, args) else: if runner: # Use the passed in Python "runner" to run the script. python_exec = runner else: # Use the current system Python to run the script. python_exec = sys.executable if interactive: # Start the script in interactive Python mode. args = ['-i', self.script, ] + command_args else: # Just run the command with no additional flags. args = [self.script, ] + command_args if python_args: args = python_args + args self.process.start(python_exec, args) self.running = True
"button.</p>" "<p>Before doing so it sets the <tt>PYQTDESIGNERPATH</tt> environment " "variable to the <tt>python</tt> directory that is part of this " "example. This directory contains all the example Python plugin " "modules.</p>" "<p>It also sets the <tt>PYTHONPATH</tt> environment variable to the " "<tt>widgets</tt> directory that is also part of this example. This " "directory contains the Python modules that implement the example " "custom widgets.</p>" "<p>All of the example custom widgets should then appear in " "Designer's widget box in the <b>PyQt Examples</b> group.</p>") # Tell Qt Designer where it can find the directory containing the plugins and # Python where it can find the widgets. base = os.path.dirname(__file__) env = QProcessEnvironment.systemEnvironment() env.insert('PYQTDESIGNERPATH', os.path.join(base, 'python')) env.insert('PYTHONPATH', os.path.join(base, 'widgets')) # Start Designer. designer = QProcess() designer.setProcessEnvironment(env) designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath) if sys.platform == 'darwin': designer_bin += '/Designer.app/Contents/MacOS/Designer' else: designer_bin += '/designer' designer.start(designer_bin)
def _update_process_environment(self): """(internal) initializes the environment for the process.""" se = QProcessEnvironment.systemEnvironment() for k, v in self.environment.items(): se.remove(k) if v is None else se.insert(k, v) self._process.setProcessEnvironment(se)
def start_process(self, script_name, working_directory, interactive=True, debugger=False, command_args=None, envars=None, runner=None, python_args=None): """ Start the child Python process. Will run the referenced Python script_name within the context of the working directory. If interactive is True (the default) the Python process will run in interactive mode (dropping the user into the REPL when the script completes). If debugger is True (the default is False) then the script will run within a debug runner session. If there is a list of command_args (the default is None), then these will be passed as further arguments into the script to be run. If there is a list of environment variables, these will be part of the context of the new child process. If runner is given, this is used as the command to start the Python process. If python_args is given, these are passed as arguments to the Python runtime used to launch the child process. """ if not envars: # Envars must be a list if not passed a value. envars = [] self.script = os.path.abspath(os.path.normcase(script_name)) logger.info('Running script: {}'.format(self.script)) if interactive: logger.info('Running with interactive mode.') if command_args is None: command_args = [] logger.info('Command args: {}'.format(command_args)) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.MergedChannels) # Force buffers to flush immediately. env = QProcessEnvironment.systemEnvironment() env.insert('PYTHONUNBUFFERED', '1') env.insert('PYTHONIOENCODING', 'utf-8') if sys.platform == 'win32' and 'pythonw.exe' in sys.executable: # On Windows, if installed via NSIS then Python is always run in # isolated mode via pythonw.exe so none of the expected directories # are on sys.path. To mitigate, Mu attempts to drop a mu.pth file # in a location taken from Windows based settings. This file will # contain the "other" directories to include on the Python path, # such as the working_directory and, if different from the # working_directory, the directory containing the script to run. try: if site.ENABLE_USER_SITE: # Ensure the USER_SITE directory exists. os.makedirs(site.getusersitepackages(), exist_ok=True) site_path = site.USER_SITE path_file = os.path.join(site_path, 'mu.pth') logger.info('Python paths set via {}'.format(path_file)) # Copy current Python paths. Use a set to avoid # duplications. paths_to_use = set([os.path.normcase(p) for p in sys.path]) # Add Mu's working directory. paths_to_use.add(os.path.normcase(working_directory)) # Add the directory containing the script. paths_to_use.add(os.path.normcase( os.path.dirname(self.script))) # Dropping a mu.pth file containing the paths_to_use # into USER_SITE will add such paths to sys.path in the # child process. with open(path_file, 'w') as mu_pth: for p in paths_to_use: mu_pth.write(p + '\n') else: logger.info("Unable to set Python paths." " Python's USER_SITE not enabled." " Check configuration with administrator.") except Exception as ex: # Log all possible errors and allow Mu to continue. This is a # "best effort" attempt to add the correct paths to the child # process, but sometimes configuration by sys-admins may cause # this to fail. logger.error('Could not set Python paths with mu.pth file.') logger.error(ex) if 'PYTHONPATH' not in envars: envars.append(('PYTHONPATH', os.pathsep.join(sys.path))) if envars: logger.info('Running with environment variables: ' '{}'.format(envars)) for name, value in envars: env.insert(name, value) logger.info('Working directory: {}'.format(working_directory)) self.process.setWorkingDirectory(working_directory) self.process.setProcessEnvironment(env) self.process.readyRead.connect(self.try_read_from_stdout) self.process.finished.connect(self.finished) logger.info('Python path: {}'.format(sys.path)) if debugger: # Start the mu-debug runner for the script. parent_dir = os.path.join(os.path.dirname(__file__), '..') mu_dir = os.path.abspath(parent_dir) runner = os.path.join(mu_dir, 'mu-debug.py') python_exec = sys.executable args = [runner, self.script, ] + command_args self.process.start(python_exec, args) else: if runner: # Use the passed in Python "runner" to run the script. python_exec = runner else: # Use the current system Python to run the script. python_exec = sys.executable if interactive: # Start the script in interactive Python mode. args = ['-i', self.script, ] + command_args else: # Just run the command with no additional flags. args = [self.script, ] + command_args if python_args: args = python_args + args self.process.start(python_exec, args) self.running = True