コード例 #1
0
 def _set_up_run(self, **envvars):
     """Set up common elements of a QProcess run"""
     self.process = QProcess()
     environment = QProcessEnvironment(self.environment)
     for k, v in envvars.items():
         environment.insert(k, v)
     self.process.setProcessEnvironment(environment)
     self.process.setProcessChannelMode(QProcess.MergedChannels)
コード例 #2
0
 def _set_up_run(self, **envvars):
     """Run the process with the command and args"""
     self.process = QProcess(self)
     environment = QProcessEnvironment(self.environment)
     for k, v in envvars.items():
         environment.insert(k, v)
     self.process.setProcessEnvironment(environment)
     self.process.setProcessChannelMode(QProcess.MergedChannels)
コード例 #3
0
def launch_game(app_name: str,
                lgd_core: LegendaryCore,
                offline: bool = False,
                skip_version_check: bool = False,
                username_override=None,
                wine_bin: str = None,
                wine_prfix: str = None,
                language: str = None,
                wrapper=None,
                no_wine: bool = os.name == "nt",
                extra: [] = None):
    game = lgd_core.get_installed_game(app_name)
    if not game:
        print("Game not found")
        return None
    if game.is_dlc:
        print("Game is dlc")
        return None
    if not os.path.exists(game.install_path):
        print("Game doesn't exist")
        return None

    if not offline:
        print("logging in")
        if not lgd_core.login():
            return None
        if not skip_version_check and not core.is_noupdate_game(app_name):
            # check updates
            try:
                latest = lgd_core.get_asset(app_name, update=True)
            except ValueError:
                print("Metadata doesn't exist")
                return None
            if latest.build_version != game.version:
                print("Please update game")
                return None
    params, cwd, env = lgd_core.get_launch_parameters(app_name=app_name,
                                                      offline=offline,
                                                      extra_args=extra,
                                                      user=username_override,
                                                      wine_bin=wine_bin,
                                                      wine_pfx=wine_prfix,
                                                      language=language,
                                                      wrapper=wrapper,
                                                      disable_wine=no_wine)
    process = QProcess()
    process.setWorkingDirectory(cwd)
    environment = QProcessEnvironment()
    for e in env:
        environment.insert(e, env[e])
    process.setProcessEnvironment(environment)
    process.start(params[0], params[1:])
    return process
コード例 #4
0
 def __main_execution(self):
     python_exec = self.python_exec
     file_directory = file_manager.get_folder(self._filename)
     self._process.setWorkingDirectory(file_directory)
     # Force python to unbuffer stding ad stdout
     options = ['-u'] + settings.EXECUTION_OPTIONS.split()
     self._process.setProgram(python_exec)
     self._process.setArguments(options + [self._filename])
     environment = QProcessEnvironment()
     system_environemnt = self._process.systemEnvironment()
     for env in system_environemnt:
         key, value = env.split('=', 1)
         environment.insert(key, value)
     self._process.setProcessEnvironment(environment)
     self._process.start()
コード例 #5
0
 def __main_execution(self):
     self.__current_process = self.main_process
     if not self.only_text:
         # In case a text is executed and not a file or project
         file_directory = file_manager.get_folder(self.filename)
         self.main_process.setWorkingDirectory(file_directory)
     self.main_process.setProgram(self.python_exec)
     self.main_process.setArguments(self.arguments)
     environment = QProcessEnvironment()
     system_environment = self.main_process.systemEnvironment()
     for env in system_environment:
         key, value = env.split("=", 1)
         environment.insert(key, value)
     self.main_process.setProcessEnvironment(environment)
     self.main_process.start()
コード例 #6
0
    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()
コード例 #7
0
    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()
コード例 #8
0
    def run(self, *args, cwd=None):
        env = QProcessEnvironment().systemEnvironment()
        for k, v in self.get_subprocess_env().items():
            env.insert(k, v)

        self.process = QProcess(self)
        self.process.setProcessEnvironment(env)
        if cwd:
            self.process.setWorkingDirectory(cwd)
        # self.process.stateChanged.connect(self.stateChanged)
        self.process.readyReadStandardOutput.connect(self.on_stdout_read)
        self.process.readyReadStandardError.connect(self.on_stderr_read)
        self.process.finished.connect(self.on_process_end)

        self.clear()
        self.process.start(args[0], args[1:], QIODevice.ReadWrite)
コード例 #9
0
    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"
コード例 #10
0
ファイル: __init__.py プロジェクト: 59de44955ebd/qpdb
 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()
コード例 #11
0
ファイル: adduser.py プロジェクト: rbircher/Utilities
    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")
コード例 #12
0
    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 = ""
コード例 #13
0
ファイル: main.py プロジェクト: ajfite/simf-python-gui
    def start_capture(self):
        # Retrieves the password via a QDialog
        self.passprompt = PasswordWindow()
        self.passprompt.exec_()  # Wait for the password dialog to finish
        if self.passprompt.rejectstat:  # Cancel was pressed
            return
        password = self.passprompt.passLine.text()  # Grab the password

        env = QProcessEnvironment.systemEnvironment()
        self.simfProcess.setProcessEnvironment(env)
        self.simfProcess.setWorkingDirectory(Config.lepton_grabber_working_dir)
        self.simfProcess.setProcessChannelMode(QProcess.MergedChannels)
        # Note this is a kinda hacky way to get the script to execute
        # with sudo permissions, likely a better way to do this at the system
        # level
        self.simfProcess.start(Config.bash_path)
        self.simfProcess.writeData(
            ("printf -v pw \"%q\\n\" \"" + password + "\"\n").encode('utf-8'))
        self.simfProcess.writeData(
            ("echo $pw | " + "\"" + Config.sudo_path + "\" -S " + "\"" +
             Config.python_path + "\"" + " frame_grabber.py"
             " --dbg_interval " + str(Config.dbg_interval) + "" +
             (" --dbg_png" if Config.dbg_png else "") +
             " --dbg_ffc_interval " + str(Config.dbg_ffc_interval) +
             " --dbg_capture_count " + str(Config.dbg_capture_count) +
             " --dbg_serial_csv " + str(int(Config.dbg_serial_csv)) +
             " --dbg_lepton_set " + str(Config.dbg_lepton_set) +
             (" --dbg_testmode1" if Config.dbg_testmode1 else "") +
             (" --dbg_print" if Config.dbg_print else "") +
             (" --dbg_ser_noavg" if Config.dbg_ser_noavg else "") +
             (" --dbg_no_serial" if Config.dbg_no_serial else "") +
             "\n").encode('utf-8'))

        self.simfProcess.writeData("exit\n".encode('utf-8'))
コード例 #14
0
ファイル: SvnPropListDialog.py プロジェクト: Darriall/eric
 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 = ""
コード例 #15
0
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()
コード例 #16
0
    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.final_stdout: str = ""
        self.final_stderr: str = ""

        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)
コード例 #17
0
ファイル: SyncPlugin.py プロジェクト: wanming2008/qb-sync
    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
コード例 #18
0
ファイル: SyncPlugin.py プロジェクト: aguinet/ret-sync
    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
コード例 #19
0
ファイル: SyncPlugin.py プロジェクト: qq449243251/ret-sync
    def init_broker(self):
        rs_debug("init_broker")
        modname = self.input.text()
        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
コード例 #20
0
ファイル: run_widget.py プロジェクト: ninja-ide/ninja-ide
 def __main_execution(self):
     self.__elapsed.start()
     self.__current_process = self.main_process
     if not self.only_text:
         # In case a text is executed and not a file or project
         file_directory = file_manager.get_folder(self.filename)
         self.main_process.setWorkingDirectory(file_directory)
     self.main_process.setProgram(self.python_exec)
     self.main_process.setArguments(self.arguments)
     environment = QProcessEnvironment()
     system_environment = self.main_process.systemEnvironment()
     for env in system_environment:
         key, value = env.split("=", 1)
         environment.insert(key, value)
     self.main_process.setProcessEnvironment(environment)
     self.main_process.start()
コード例 #21
0
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')
コード例 #22
0
ファイル: MainWindow.py プロジェクト: lzx8589561/PyQtClient
    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])
コード例 #23
0
    def __init__(self,
                 win_id,
                 what,
                 *,
                 verbose=False,
                 additional_env=None,
                 parent=None):
        super().__init__(parent)
        self._win_id = win_id
        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)
コード例 #24
0
 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)
コード例 #25
0
 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")
コード例 #26
0
ファイル: SvnDialog.py プロジェクト: pycom/EricShort
 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
コード例 #27
0
 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
コード例 #28
0
 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
コード例 #29
0
 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
コード例 #30
0
ファイル: run_widget.py プロジェクト: resourceldg/ninja-ide
 def __main_execution(self):
     self._current_process = self._process
     file_directory = file_manager.get_folder(self._filename)
     self._process.setWorkingDirectory(file_directory)
     # Force python to unbuffer stding ad stdout
     options = ['-u'] + settings.EXECUTION_OPTIONS.split()
     # Set python exec and arguments
     program_params = [
         param.strip() for param in self._params.split(',') if param
     ]
     self._process.setProgram(self.python_exec)
     self._process.setArguments(options + [self._filename] + program_params)
     environment = QProcessEnvironment()
     system_environemnt = self._process.systemEnvironment()
     for env in system_environemnt:
         key, value = env.split('=', 1)
         environment.insert(key, value)
     self._process.setProcessEnvironment(environment)
     # Start!
     self._process.start()
コード例 #31
0
 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())
コード例 #32
0
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)
コード例 #33
0
    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)

        if not self.pythonExec:
            self.pythonExec = settings.PYTHON_EXEC
        #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

        env = QProcessEnvironment()
        system_environemnt = self._proc.systemEnvironment()
        for e in system_environemnt:
            key, value = e.split('=', 1)
            env.insert(key, value)
        if self.PYTHONPATH:
            envpaths = [path for path in self.PYTHONPATH.splitlines()]
            for path in envpaths:
                env.insert('PYTHONPATH', path)
        env.insert('PYTHONIOENCODING', 'utf-8')
        env.insert('PYTHONPATH', ':'.join(sys.path))
        self._proc.setProcessEnvironment(env)

        self._proc.start(
            self.pythonExec, options + [self.fileName] +
            [p.strip() for p in self.programParams.split(',') if p])
コード例 #34
0
ファイル: menumanager.py プロジェクト: CarlosAndres12/pyqt5
    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])
コード例 #35
0
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)
コード例 #36
0
ファイル: launcher.py プロジェクト: chipolux/source-tools
 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,
         )
コード例 #37
0
 def __startProcess(self, program, arguments, environment=None):
     """
     Private method to start the debugger client process.
     
     @param program name of the executable to start (string)
     @param arguments arguments to be passed to the program (list of string)
     @param environment dictionary of environment settings to pass
         (dict of string)
     @return the process object (QProcess) or None
     """
     proc = QProcess()
     if environment is not None:
         env = QProcessEnvironment()
         for key, value in list(environment.items()):
             env.insert(key, value)
         proc.setProcessEnvironment(env)
     args = []
     for arg in arguments:
         args.append(arg)
     proc.start(program, args)
     if not proc.waitForStarted(10000):
         proc = None
     
     return proc
コード例 #38
0
ファイル: testprocess.py プロジェクト: Dietr1ch/qutebrowser
    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()
コード例 #39
0
ファイル: userscripts.py プロジェクト: larryhynes/qutebrowser
    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)
コード例 #40
0
ファイル: HgUtilities.py プロジェクト: pycom/EricShort
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)
コード例 #41
0
ファイル: nplugins.py プロジェクト: LeftRadio/ngl_utils
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())
コード例 #42
0
ファイル: guiprocess.py プロジェクト: lahwaacz/qutebrowser
    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)
コード例 #43
0
ファイル: menumanager.py プロジェクト: CarlosAndres12/pyqt5
    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])
コード例 #44
0
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
コード例 #45
0
ファイル: run_widget.py プロジェクト: Salmista-94/Ninja_PyQt5
    def __main_execution(self):
        """Execute the project."""
        self.output.setCurrentCharFormat(self.output.plain_format)
        message = ''
        if self.__preScriptExecuted:
            self.__preScriptExecuted = False
            message = _translate("RunWidget", 
                "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

        env = QProcessEnvironment()
        system_environemnt = self._proc.systemEnvironment()
        for e in system_environemnt:
            key, value = e.split('=', 1)
            env.insert(key, value)
        if self.PYTHONPATH:
            envpaths = [path for path in self.PYTHONPATH.splitlines()]
            for path in envpaths:
                env.insert('PYTHONPATH', path)
        env.insert('PYTHONIOENCODING', 'utf-8')
        self._proc.setProcessEnvironment(env)

        self._proc.start(self.pythonPath, options + [self.fileName] +
            [p.strip() for p in self.programParams.split(',') if p])
コード例 #46
0
ファイル: testprocess.py プロジェクト: IsSuEat/qutebrowser
    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()
コード例 #47
0
ファイル: panes.py プロジェクト: ZanderBrown/mu
    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
コード例 #48
0
ファイル: panes.py プロジェクト: martinohanlon/mu
    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
コード例 #49
0
ファイル: plugins.py プロジェクト: Axel-Erfurt/pyqt5
        "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)
コード例 #50
0
ファイル: job.py プロジェクト: AlexSchr/frescobaldi
 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)