Python subprocess 模块,SW_HIDE 实例源码

我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用subprocess.SW_HIDE

项目:SublimePhpArrayConverter    作者:gh640    | 项目源码 | 文件源码
def prepare_subprocess_args(self):
        popen_args = {
            'args': self.get_php_cmd(),
            'env': self.get_env(),
            'stdin': subprocess.PIPE,
            'stdout': subprocess.PIPE,
            'stderr': subprocess.PIPE,
        }

        # Prevent cmd.exe window popup on Windows.
        if is_windows():
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            popen_args['startupinfo'] = startupinfo

        return popen_args
项目:LSP    作者:tomv564    | 项目源码 | 文件源码
def start_server(server_binary_args, working_dir, env):
    debug("starting " + str(server_binary_args))
    si = None
    if os.name == "nt":
        si = subprocess.STARTUPINFO()  # type: ignore
        si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW  # type: ignore
    try:
        process = subprocess.Popen(
            server_binary_args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            cwd=working_dir,
            env=env,
            startupinfo=si)
        return Client(process, working_dir)

    except Exception as err:
        sublime.status_message("Failed to start LSP server {}".format(str(server_binary_args)))
        exception_log("Failed to start server", err)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def start(self):
        WorkerClient.stop_worker = False

        node_path = global_vars.get_node_path()
        if os.name == "nt":
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
            self.server_proc = subprocess.Popen(
                [node_path, self.script_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, startupinfo=si
            )
        else:
            self.server_proc = subprocess.Popen(
                [node_path, self.script_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

        # start reader thread
        if self.server_proc and (not self.server_proc.poll()):
            log.debug("worker proc " + str(self.server_proc))
            log.debug("starting worker thread")
            workerThread = threading.Thread(target=WorkerClient.__reader, args=(
                self.server_proc.stdout, self.msgq, self.eventq, self.asyncReq, self.server_proc, self.event_handlers))
            workerThread.daemon = True
            workerThread.start()
项目:PJON-python    作者:Girgitt    | 项目源码 | 文件源码
def __init__(self, suproc_command, stdin_queue, stdout_queue, parent):
        threading.Thread.__init__(self)
        self.setDaemon(False) # we want it to survive parent's death so it can detect innactivity and terminate subproccess
        self.setName('pjon_piper_thd')
        self._subproc_command = suproc_command
        self._birthtime = None
        self._stopped = False
        self._start_failed = False
        self._pipe = None
        self._stdout_queue = stdout_queue
        self._stdin_queue = stdin_queue
        self._parent = parent
        if sys.platform == 'win32':
            self._startupinfo = subprocess.STARTUPINFO()
            self._startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self._startupinfo.wShowWindow = subprocess.SW_HIDE

        self.log = logging.getLogger(self.name)
        self.log.handlers = []
        self.log.addHandler(logging.NullHandler())
        #self.log.propagate = False
        self.log.setLevel(logging.INFO)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def stopVPNn(n):
    # Stop the platform VPN task.
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.LINUX or p == platforms.RPI:
            if useBigHammer(): n = "9"
            command = "killall -" + n + " openvpn"
            if useSudo(): command = "sudo " + command
            debugTrace("(Linux) Stopping VPN with " + command)
            os.system(command)
        if p == platforms.WINDOWS:
            # This call doesn't pay any attention to the size of the hammer.
            # Probably for Windows, if n is 15, then I should omit the /F but
            # I've not noticed any problems using /F so the n is ignored
            command = "taskkill /F /T /IM openvpn*"
            debugTrace("(Windows) Stopping VPN with " + command)
            args = shlex.split(command)
            proc = subprocess.Popen(args, creationflags=subprocess.SW_HIDE, shell=True)

        # **** ADD MORE PLATFORMS HERE ****

    return
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def startVPN(vpn_profile):
    # Call the platform VPN to start the VPN
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.RPI or p == platforms.LINUX:
            command=getOpenVPNPath() + " \"" + vpn_profile + "\" > " + getVPNLogFilePath() + " &"
            if useSudo() : command = "sudo " + command            
            debugTrace("(Linux) Starting VPN with " + command)
            os.system(command)
        if p == platforms.WINDOWS:   
            command=getOpenVPNPath() + " \"" + vpn_profile + "\""
            debugTrace("(Windows) Starting VPN with " + command)
            args = shlex.split(command)
            outfile = open(getVPNLogFilePath(),'w')
            proc = subprocess.Popen(args, stdout=outfile, creationflags=subprocess.SW_HIDE, shell=True)

        # **** ADD MORE PLATFORMS HERE ****

    else:
        # This bit is just to help with debug during development.
        command=getOpenVPNPath() + " \"" + vpn_profile + "\" > " + getVPNLogFilePath()
        debugTrace("Faking starting VPN with " + command)
    return
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def executeCmd(cmd):
    command=['cmd.exe', '/c'] + cmd.split()
    res = subprocess.check_output(command, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, universal_newlines=True)
    # info=subprocess.STARTUPINFO()
    # info.dwFlags=subprocess.STARTF_USESHOWWINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
    # info.wShowWindow=subprocess.SW_HIDE
    # p=subprocess.Popen(command, startupinfo=info, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, universal_newlines=True)
    # results, _=p.communicate()
    return res
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def start_hidden_process(path):
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
    info.wShowWindow = subprocess.SW_HIDE
    p=subprocess.Popen(path, startupinfo=info)
    return p
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def start_proc_with_token(args, hTokendupe, hidden=True):
    ##Start the process with the token.
    lpProcessInformation = PROCESS_INFORMATION()
    lpStartupInfo = STARTUPINFO()
    if hidden:
        lpStartupInfo.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
        lpStartupInfo.wShowWindow = subprocess.SW_HIDE

    CREATE_NEW_CONSOLE = 0x00000010
    CREATE_UNICODE_ENVIRONMENT = 0x00000400
    NORMAL_PRIORITY_CLASS = 0x00000020

    dwCreationflag = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE

    userenv = WinDLL('userenv', use_last_error=True)
    userenv.CreateEnvironmentBlock.argtypes = (POINTER(c_void_p), c_void_p, c_int)
    userenv.DestroyEnvironmentBlock.argtypes = (c_void_p,)
    cenv = c_void_p()

    success = userenv.CreateEnvironmentBlock(byref(cenv), hTokendupe, 0)
    if not success:
        raise WinError()

    success = windll.advapi32.CreateProcessAsUserA(hTokendupe, None, ' '.join(args), None, None, True, dwCreationflag, cenv, None, byref(lpStartupInfo), byref(lpProcessInformation))
    if not success:
        raise WinError()

    print "[+] process created PID: " + str(lpProcessInformation.dwProcessId)
    return lpProcessInformation.dwProcessId
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def start_hidden_process(path):
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
    info.wShowWindow = subprocess.SW_HIDE
    p=subprocess.Popen(path, startupinfo=info)
    return p
项目:DXMate    作者:jtowers    | 项目源码 | 文件源码
def start_server():
    deleteDbIfExists()
    working_dir = os.path.join(util.get_plugin_folder(), 'apex-jorje-lsp.jar')
    java_cmd = 'java'
    java_path = util.get_setting('java_path')
    util.debug(java_path)
    if java_path != '':
        java_cmd = os.path.join(java_path, java_cmd)

    util.debug('using java path: ', java_cmd)
    args = [java_cmd, '-cp', working_dir, '-Ddebug.internal.errors=true','-Ddebug.semantic.errors=false',
            'apex.jorje.lsp.ApexLanguageServerLauncher']
    util.debug("starting " + str(args))
    si = None
    if os.name == "nt":
        si = subprocess.STARTUPINFO()  # type: ignore
        si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW  # type: ignore
    try:
        process = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            cwd=util.dxProjectFolder(),
            startupinfo=si)
        return Client(process)

    except Exception as err:
        util.debug(err)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def start_proc_with_token(args, hTokendupe, hidden=True):
    ##Start the process with the token.
    lpProcessInformation = PROCESS_INFORMATION()
    lpStartupInfo = STARTUPINFO()
    if hidden:
        lpStartupInfo.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
        lpStartupInfo.wShowWindow = subprocess.SW_HIDE

    CREATE_NEW_CONSOLE = 0x00000010
    CREATE_UNICODE_ENVIRONMENT = 0x00000400
    NORMAL_PRIORITY_CLASS = 0x00000020

    dwCreationflag = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE

    userenv = WinDLL('userenv', use_last_error=True)
    userenv.CreateEnvironmentBlock.argtypes = (POINTER(c_void_p), c_void_p, c_int)
    userenv.DestroyEnvironmentBlock.argtypes = (c_void_p,)
    cenv = c_void_p()

    success = userenv.CreateEnvironmentBlock(byref(cenv), hTokendupe, 0)
    if not success:
        raise WinError()

    success = windll.advapi32.CreateProcessAsUserA(hTokendupe, None, ' '.join(args), None, None, True, dwCreationflag, cenv, None, byref(lpStartupInfo), byref(lpProcessInformation))
    if not success:
        raise WinError()

    print "[+] process created PID: " + str(lpProcessInformation.dwProcessId)
    return lpProcessInformation.dwProcessId
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def start_hidden_process(path):
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
    info.wShowWindow = subprocess.SW_HIDE
    p=subprocess.Popen(path, startupinfo=info)
    return p
项目:sublime-rust-fmt    作者:Mitranim    | 项目源码 | 文件源码
def process_startup_info():
    if not is_windows():
        return None
    startupinfo = sub.STARTUPINFO()
    startupinfo.dwFlags |= sub.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = sub.SW_HIDE
    return startupinfo
项目:eduActiv8    作者:imiolek-ireneusz    | 项目源码 | 文件源码
def start_server(self):
        if self.android is None:
            if self.enabled and self.lang.voice is not None:
                # voices = ["-s 190 -a 100 -p 75 -ven+m1 ", "-s 170 -a 100 -p 80 -ven+m2 ","-s 175 -a 100 -p 80 -ven+m3 ","-s 190 -a 100 -p 60 -ven+f1 ","-s 170 -a 100 -p 75 -ven+f2 ","-s 170 -a 100 -p 80 -ven+m2 "]
                cmd = ['espeak']
                cmd.extend(self.lang.voice)
                try:
                    # IS_WIN32 = 'win32' in str(sys.platform).lower() #maybe sys.platform is more secure
                    is_win = platform.system() == "Windows"
                    if is_win:
                        startupinfo = subprocess.STARTUPINFO()
                        startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
                        startupinfo.wShowWindow = subprocess.SW_HIDE
                        kwargs = {}
                        kwargs['startupinfo'] = startupinfo
                        # self.process = subprocess.Popen(cmd, shell=True, bufsize=0, close_fds=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
                        self.process = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                                        stderr=subprocess.PIPE, startupinfo=startupinfo)
                    else:
                        self.process = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                                        stderr=subprocess.PIPE)

                    # self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    self.started = True

                except:
                    self.enabled = False
                    self.started = False
                    print(
                        "eduActiv8: You may like to install espeak to get some extra functionality, however this is not required to successfully use the game.")
                    # stdout and stderr only used to hide the messages from terminal
            else:
                self.process = None
项目:idascripts    作者:ctfhacker    | 项目源码 | 文件源码
def subprocess(program, cwd, environment, newlines, joined, shell=True, show=False):
        """Create a subprocess using subprocess.Popen."""
        stderr = subprocess.STDOUT if joined else subprocess.PIPE
        if os.name == 'nt':
            si = subprocess.STARTUPINFO()
            si.dwFlags = subprocess.STARTF_USESHOWWINDOW
            si.wShowWindow = 0 if show else subprocess.SW_HIDE
            cf = subprocess.CREATE_NEW_CONSOLE if show else 0
            return subprocess.Popen(program, universal_newlines=newlines, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=False, startupinfo=si, creationflags=cf, cwd=cwd, env=environment)
        return subprocess.Popen(program, universal_newlines=newlines, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=True, cwd=cwd, env=environment)
项目:PCControl    作者:renhongl    | 项目源码 | 文件源码
def __subprocess_call(self, *args, **kwargs):  
        if self.IS_WIN32:  
            startupinfo = subprocess.STARTUPINFO()  
            startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW  
            startupinfo.wShowWindow = subprocess.SW_HIDE  
            kwargs['startupinfo'] = startupinfo  
        retcode = subprocess.call(*args, **kwargs)  
        return retcode
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def run_command(command, shell=True, cwd=path.curdir, env=environ):
        """Run a generic command in a subprocess.

        Args:
            command (str): command to run

        Returns:
            str: raw command output
        """
        try:
            stdin = None
            startupinfo = None
            if isinstance(command, list):
                command = subprocess.list2cmdline(command)
                log.debug("running command: \n%s", command)
            if sublime.platform() == "windows":
                # Don't let console window pop-up briefly.
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = subprocess.SW_HIDE
                stdin = subprocess.PIPE
            output = subprocess.check_output(command,
                                             stdin=stdin,
                                             stderr=subprocess.STDOUT,
                                             shell=shell,
                                             cwd=cwd,
                                             env=env,
                                             startupinfo=startupinfo)
            output_text = ''.join(map(chr, output))
        except subprocess.CalledProcessError as e:
            output_text = e.output.decode("utf-8")
            log.debug("command finished with code: %s", e.returncode)
            log.debug("command output: \n%s", output_text)
        return output_text
项目:nvda-ocr    作者:nvaccess    | 项目源码 | 文件源码
def script_ocrNavigatorObject(self, gesture):
        nav = api.getNavigatorObject()
        left, top, width, height = nav.location
        img = ImageGrab.grab(bbox=(left, top, left + width, top + height))
        # Tesseract copes better if we convert to black and white...
        img = img.convert(mode='L')
        # and increase the size.
        img = img.resize((width * IMAGE_RESIZE_FACTOR, height * IMAGE_RESIZE_FACTOR), Image.BICUBIC)
        baseFile = os.path.join(tempfile.gettempdir(), "nvda_ocr")
        try:
            imgFile = baseFile + ".bmp"
            img.save(imgFile)

            ui.message(_("Running OCR"))
            lang = getConfig()['language']
            # Hide the Tesseract window.
            si = subprocess.STARTUPINFO()
            si.dwFlags = subprocess.STARTF_USESHOWWINDOW
            si.wShowWindow = subprocess.SW_HIDE
            subprocess.check_call((TESSERACT_EXE, imgFile, baseFile, "-l", lang, "hocr"),
                startupinfo=si)
        finally:
            try:
                os.remove(imgFile)
            except OSError:
                pass
        try:
            hocrFile = baseFile + ".html"

            parser = HocrParser(file(hocrFile).read(),
                left, top)
        finally:
            try:
                os.remove(hocrFile)
            except OSError:
                pass

        # Let the user review the OCR output.
        nav.makeTextInfo = lambda position: OcrTextInfo(nav, position, parser)
        api.setReviewPosition(nav.makeTextInfo(textInfos.POSITION_FIRST))
        ui.message(_("Done"))
项目:GoFeather    作者:frou    | 项目源码 | 文件源码
def platform_startupinfo():
    if sys.platform == 'win32':
        si = subprocess.STARTUPINFO()
        # Stop a visible console window from appearing.
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        return si
    else:
        return None
项目:languagetool-sublime    作者:gtarawneh    | 项目源码 | 文件源码
def run(self, edit):
        settings = sublime.load_settings(lt_settings_file)
        jarPath = settings.get('languagetool_jar')
        if jarPath:
            if os.path.isfile(jarPath):
                sublime.status_message('Starting local LanguageTool server ...')
                cmd = ['java', '-jar', jarPath, '-t']
                if sublime.platform() == "windows":
                    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, creationflags=subprocess.SW_HIDE)
                else:
                    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                showPanelText('Error, could not find LanguageTool\'s JAR file (%s)\n\nPlease install LT in this directory or modify the `languagetool_jar` setting.' % jarPath)
项目:dictationbridge-nvda    作者:dictationbridge    | 项目源码 | 文件源码
def _onInstallDragonCommands():
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    si.wShowWindow = subprocess.SW_HIDE
    dragonDir = r"C:\Program Files (x86)\Nuance\NaturallySpeaking15\Program"
    #Translators: Title of an error dialog shown in dictation bridge.
    DB_ERROR_TITLE = _("Dictation Bridge Error")
    if not os.path.exists(dragonDir):
        dragonDir.replace(r" (x86)", "")
    if not os.path.exists(dragonDir):
        #Translators: Message given to the user when the addon can't find an installed copy of dragon.
        gui.messageBox(_("Cannot find dragon installed on your machine. Please install dragon and then try this process again."),
            DB_ERROR_TITLE)
        return
    xml2dat = os.path.join(dragonDir, "mycmdsxml2dat.exe")
    nsadmin = os.path.join(dragonDir, "nsadmin.exe")

    #Translators: The official name of Dragon in your language, this probably should be left as Dragon.
    thisProgram = _("Dragon")
    if os.path.exists(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")):
            os.remove(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"))
    try:
        subprocess.check_call([
            xml2dat,
            os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"),
            os.path.join(addonRootDir, "dragon_dictationBridgeCommands.xml"),
            ], startupinfo=si)
        #Fixme: might need to get the users language, and put them there for non-english locales.
        d=config.execElevated(nsadmin,
            ["/commands", os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"), "/overwrite=yes"],
            wait=True, handleAlreadyElevated=True)

        successDialog(thisProgram)
    except:
        #Translators: Message shown if dragon commands failed to install.
        gui.messageBox(_("There was an error while performing the addition of dragon commands into dragon. Are you running as an administrator? If so, please send the error in your log to the dictation bridge team as a bug report."),
            DB_ERROR_TITLE)
        raise
    finally:
        if os.path.exists(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")):
            os.remove(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"))
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def popen(cmd, stdout=None, stderr=None, output_stream=STREAM_BOTH, env=None, extra_env=None):
    """Open a pipe to an external process and return a Popen object."""

    info = None

    if os.name == 'nt':
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = subprocess.SW_HIDE

    if output_stream == STREAM_BOTH:
        stdout = stdout or subprocess.PIPE
        stderr = stderr or subprocess.PIPE
    elif output_stream == STREAM_STDOUT:
        stdout = stdout or subprocess.PIPE
        stderr = subprocess.DEVNULL
    else:  # STREAM_STDERR
        stdout = subprocess.DEVNULL
        stderr = stderr or subprocess.PIPE

    if env is None:
        env = create_environment()

    if extra_env is not None:
        env.update(extra_env)

    try:
        return subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=stdout,
            stderr=stderr,
            startupinfo=info,
            env=env
        )
    except Exception as err:
        from . import persist
        persist.printf('ERROR: could not launch', repr(cmd))
        persist.printf('reason:', str(err))
        persist.printf('PATH:', env.get('PATH', ''))


# view utils
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def interactive_open(program=None, encoding=None):
    try:
        if program is None:
            if sys.platform=="win32":
                program="cmd.exe"
            else:
                if "SHELL" in os.environ:
                    program=os.environ["SHELL"]
                else:
                    program="/bin/sh"
                encoding=None

        fullargs=[program]
        if sys.platform=="win32":
            try:
                #couldn't find a better way, none of the following methods worked for me : kernel32.SetConsoleOutputCP(), locale.getpreferredencoding(), sys.stdout.encoding
                encoding="cp"+str(re.findall(r".*:\s*([0-9]+)",subprocess.check_output("chcp", shell=True))[0])
            except:
                pass
            if program.endswith("powershell") or program.endswith("powershell.exe"):
                fullargs=["powershell.exe", "-C", "-"] # trick to make powershell work without blocking
        if encoding is None:
            encoding=locale.getpreferredencoding()
        print "Opening interactive %s (with encoding %s)..."%(program,encoding)
        if sys.platform=="win32":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            p = Popen(fullargs, stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, close_fds=ON_POSIX, universal_newlines=True, startupinfo=startupinfo)
        else:
            p = Popen(fullargs, stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, close_fds=ON_POSIX, universal_newlines=True)
        q = Queue()
        q2 = Queue()
        t = Thread(target=write_output, args=(p.stdout, q))
        t.daemon = True
        t.start()

        t = Thread(target=write_output, args=(p.stderr, q2))
        t.daemon = True
        t.start()

        t = Thread(target=flush_loop, args=(q, encoding))
        t.daemon = True
        t.start()

        t = Thread(target=flush_loop, args=(q2, encoding))
        t.daemon = True
        t.start()

        while True:
            line = raw_input()
            p.stdin.write(line+"\n")
            p.stdin.flush()
            if line.strip()=="exit":
                break
    except Exception as e:
        print(traceback.format_exc())
项目:rekit-sublime    作者:supnate    | 项目源码 | 文件源码
def run(self):
    si = None
    if hasattr(subprocess, "STARTUPINFO"):
      si = subprocess.STARTUPINFO()
      si.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    try:
      #si.wShowWindow = subprocess.SW_HIDE # default
      envPATH = os.environ['PATH'] + LOCAL_PATH
      s = sublime.load_settings("Rekit.sublime-settings")
      if s.get('node_dir') and envPATH.find(s.get('node_dir')) == -1:
        envPATH = envPATH + os.pathsep + s.get('node_dir')
      if s.get('npm_dir') and envPATH.find(s.get('npm_dir')) == -1:
        envPATH = envPATH + os.pathsep + s.get('npm_dir')

      # https://docs.python.org/2/library/subprocess.html
      # Note If specified, env must provide any variables required for the program to execute. 
      # On Windows, in order to run a side-by-side assembly the specified env **must** include a valid SystemRoot.
      envObj = {
        'PATH': envPATH,
        'SYSTEMROOT': os.environ['SYSTEMROOT']
      }

      p = subprocess.Popen(self.command, cwd=self.working_dir, env=envObj, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, startupinfo=si)
      for line in iter(p.stdout.readline, b''):
        line2 = line.decode().strip('\r\n')
        # only show output for mocha     
        if re.search(r'run_test\.js|build\.js', self.command[1]) is not None:
          show_rekit_output(line2)
      if self.on_done:
        self.on_done()

    except subprocess.CalledProcessError as e:
      # show_rekit_output(str(e))
      show_rekit_output('running node failed:')
      show_rekit_output(str(e))
      sublime.error_message(str(e))

    except OSError as e:
      if e.errno == 2:
        main_thread(sublime.error_message, "Node binary could not be found in PATH\nConsider using the node_dir and npm_dir settings for the Rekit plugin\n\nPATH is: %s" % os.environ['PATH'])
      else:
        show_rekit_output('running node failed:')
        show_rekit_output(str(e))
        raise e

    except Exception as e:
      show_rekit_output('running node failed:')
      show_rekit_output(str(e))
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def interactive_open(program=None, encoding=None):
    try:
        if program is None:
            if sys.platform=="win32":
                program="cmd.exe"
            else:
                if "SHELL" in os.environ:
                    program=os.environ["SHELL"]
                else:
                    program="/bin/sh"
                encoding=None

        fullargs=[program]
        if sys.platform=="win32":
            try:
                #couldn't find a better way, none of the following methods worked for me : kernel32.SetConsoleOutputCP(), locale.getpreferredencoding(), sys.stdout.encoding
                encoding="cp"+str(re.findall(r".*:\s*([0-9]+)",subprocess.check_output("chcp", shell=True))[0])
            except:
                pass
            if program.endswith("powershell") or program.endswith("powershell.exe"):
                fullargs=["powershell.exe", "-C", "-"] # trick to make powershell work without blocking
        if encoding is None:
            encoding=locale.getpreferredencoding()
        print "Opening interactive %s (with encoding %s)..."%(program,encoding)
        if sys.platform=="win32":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            p = Popen(fullargs, stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, close_fds=ON_POSIX, universal_newlines=True, startupinfo=startupinfo)
        else:
            p = Popen(fullargs, stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, close_fds=ON_POSIX, universal_newlines=True)
        q = Queue()
        q2 = Queue()
        t = Thread(target=write_output, args=(p.stdout, q))
        t.daemon = True
        t.start()

        t = Thread(target=write_output, args=(p.stderr, q2))
        t.daemon = True
        t.start()

        t = Thread(target=flush_loop, args=(q, encoding))
        t.daemon = True
        t.start()

        t = Thread(target=flush_loop, args=(q2, encoding))
        t.daemon = True
        t.start()

        while True:
            line = raw_input()
            p.stdin.write(line+"\n")
            p.stdin.flush()
            if line.strip()=="exit":
                break
    except Exception as e:
        print(traceback.format_exc())
项目:Electrify    作者:jyapayne    | 项目源码 | 文件源码
def compress_nw(self, electron_path):
        compression = self.get_setting('electron_compression_level')
        if compression.value == 0:
            return

        comp_dict = {'Darwin64bit': get_file('files/compressors/upx-mac'),
                     'Darwin32bit': get_file('files/compressors/upx-mac'),
                     'Linux64bit':  get_file('files/compressors/upx-linux-x64'),
                     'Linux32bit':  get_file('files/compressors/upx-linux-x32'),
                     'Windows64bit':  get_file('files/compressors/upx-win.exe'),
                     'Windows32bit':  get_file('files/compressors/upx-win.exe')
                     }

        if is_installed():
            comp_dict['Windows64bit'] = get_data_file_path('files/compressors/upx-win.exe')
            comp_dict['Windows32bit'] = get_data_file_path('files/compressors/upx-win.exe')

        plat = platform.system()+platform.architecture()[0]
        upx_version = comp_dict.get(plat, None)

        if upx_version is not None:
            upx_bin = upx_version
            os.chmod(upx_bin, 0o755)
            cmd = [upx_bin, '--lzma', u'-{}'.format(compression.value), electron_path]
            if platform.system() == 'Windows':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = subprocess.SW_HIDE
                proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        stdin=subprocess.PIPE,
                                        startupinfo=startupinfo)
            else:
                proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            self.progress_text = '\n\n'
            self.progress_text = 'Compressing files'
            while proc.poll() is None:
                self.progress_text += '.'
                time.sleep(2)
            output, err = proc.communicate()
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def popen(cmd, stdout=None, stderr=None, output_stream=STREAM_BOTH, env=None, extra_env=None):
    """Open a pipe to an external process and return a Popen object."""

    info = None

    if os.name == 'nt':
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = subprocess.SW_HIDE

    if output_stream == STREAM_BOTH:
        stdout = stdout or subprocess.PIPE
        stderr = stderr or subprocess.PIPE
    elif output_stream == STREAM_STDOUT:
        stdout = stdout or subprocess.PIPE
        stderr = subprocess.DEVNULL
    else:  # STREAM_STDERR
        stdout = subprocess.DEVNULL
        stderr = stderr or subprocess.PIPE

    if env is None:
        env = create_environment()

    if extra_env is not None:
        env.update(extra_env)

    try:
        return subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=stdout,
            stderr=stderr,
            startupinfo=info,
            env=env
        )
    except Exception as err:
        from . import persist
        persist.printf('ERROR: could not launch', repr(cmd))
        persist.printf('reason:', str(err))
        persist.printf('PATH:', env.get('PATH', ''))


# view utils
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def __init__(self, script_path):
        """
        Starts a node client (if not already started) and communicate with it.
        The script file to run is passed to the constructor.
        """
        super(ServerClient, self).__init__(script_path)

        # start node process
        pref_settings = sublime.load_settings('Preferences.sublime-settings')
        node_path = pref_settings.get('node_path')
        if node_path:
            print("Path of node executable is configured as: " + node_path)
            configured_node_path = os.path.expandvars(node_path)
            if NodeCommClient.is_executable(configured_node_path):
                node_path = configured_node_path
            else:
                node_path = None
                print("Configured node path is not a valid executable.")
        if not node_path:
            if os.name == "nt":
                node_path = "node"
            else:
                node_path = NodeCommClient.which("node")
        if not node_path:
            path_list = os.environ["PATH"] + os.pathsep + "/usr/local/bin" + os.pathsep + "$NVM_BIN"
            print("Unable to find executable file for node on path list: " + path_list)
            print("To specify the node executable file name, use the 'node_path' setting")
            self.server_proc = None
        else:
            global_vars._node_path = node_path
            print("Trying to spawn node executable from: " + node_path)
            try:
                if os.name == "nt":
                    # linux subprocess module does not have STARTUPINFO
                    # so only use it if on Windows
                    si = subprocess.STARTUPINFO()
                    si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
                    self.server_proc = subprocess.Popen([node_path, script_path],
                                                         stdin=subprocess.PIPE, stdout=subprocess.PIPE, startupinfo=si)
                else:
                    log.debug("opening " + node_path + " " + script_path)
                    self.server_proc = subprocess.Popen([node_path, script_path],
                                                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            except:
                self.server_proc = None
        # start reader thread
        if self.server_proc and (not self.server_proc.poll()):
            log.debug("server proc " + str(self.server_proc))
            log.debug("starting reader thread")
            readerThread = threading.Thread(target=ServerClient.__reader, args=(
                self.server_proc.stdout, self.msgq, self.eventq, self.asyncReq, self.server_proc, self.event_handlers))
            readerThread.daemon = True
            readerThread.start()
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def start_process(args, input_string='', env=None, cwd=None, stdout=None,
                  stderr=None):
  """Starts a subprocess like subprocess.Popen, but is threadsafe.

  The value of input_string is passed to stdin of the subprocess, which is then
  closed.

  Args:
    args: A string or sequence of strings containing the program arguments.
    input_string: A string to pass to stdin of the subprocess.
    env: A dict containing environment variables for the subprocess.
    cwd: A string containing the directory to switch to before executing the
        subprocess.
    stdout: A file descriptor, file object or subprocess.PIPE to use for the
        stdout descriptor for the subprocess.
    stderr: A file descriptor, file object or subprocess.PIPE to use for the
        stderr descriptor for the subprocess.

  Returns:
    A subprocess.Popen instance for the created subprocess.
  """
  with _popen_lock:
    logging.debug('Starting process %r with input=%r, env=%r, cwd=%r',
                  args, input_string, env, cwd)

    # Suppress the display of the console window on Windows.
    # Note: subprocess.STARTF_USESHOWWINDOW & subprocess.SW_HIDE are only
    # availalbe after Python 2.7.2 on Windows.
    if (hasattr(subprocess, 'SW_HIDE') and
        hasattr(subprocess, 'STARTF_USESHOWWINDOW')):
      startupinfo = subprocess.STARTUPINFO()
      startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
      startupinfo.wShowWindow = subprocess.SW_HIDE
    else:
      startupinfo = None

    p = subprocess.Popen(args, env=env, cwd=cwd, stdout=stdout, stderr=stderr,
                         stdin=subprocess.PIPE, startupinfo=startupinfo)
    if _SUBPROCESS_STDIN_IS_THREAD_HOSTILE:
      p.stdin.write(input_string)
      p.stdin.close()
      p.stdin = None
  if not _SUBPROCESS_STDIN_IS_THREAD_HOSTILE:
    p.stdin.write(input_string)
    p.stdin.close()
    p.stdin = None
  return p
项目:PJON-python    作者:Girgitt    | 项目源码 | 文件源码
def __init__(self, bus_addr=1, com_port=None, baud=115200):
        super(PjonPiperClient, self).__init__()
        self._pipe = None
        self._bus_addr = bus_addr
        self._serial_baud = baud
        self._piper_client_stdin_queue = Queue()
        self._piper_client_stdout_queue = Queue()
        self._receiver_function = self.dummy_receiver
        self._error_function = self.dummy_error
        self._last_watchdog_poll_ts = 0
        self._piper_stdout_watchdog_timeout = 0
        self._piper_stdout_last_received_ts = 0


        if sys.platform == 'win32':
            self._startupinfo = subprocess.STARTUPINFO()
            self._startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self._startupinfo.wShowWindow = subprocess.SW_HIDE
            self._pjon_piper_path = os.path.join(self.get_self_path(), 'pjon_piper_bin', 'win', 'PJON-piper.exe')
        elif sys.platform == 'linux2':
            #os.setpgrp()
            if(self.is_arm_platform()):
                if self.is_raspberry():
                    self._pjon_piper_path = os.path.join(self.get_self_path(), 'pjon_piper_bin', 'rpi',
                                                         'pjon_piper')
                    #print(self._pjon_piper_path)
                else:
                    NotImplementedError("Only Linux on Raspberry is supported")
            else:
                raise NotImplementedError("this version of Linux is not supported yet")
        else:
            raise NotImplementedError("platform not supported; currently provided support only for: win32")

        if sys.platform == 'win32':
            self._pipier_client_subproc_cmd = "%s %s %s %s\n" % (self._pjon_piper_path, com_port.strip(), baud, bus_addr)
        elif sys.platform == 'linux2':
            self._pipier_client_subproc_cmd = [self._pjon_piper_path, com_port.strip(), str(baud), str(bus_addr)]
        if com_port is None:
            raise ComPortUndefinedExc("missing com_port kwarg: serial port name is required")

        available_coms = self.get_coms()
        if com_port not in available_coms:
            raise ComPortNotAvailableExc("com port %s is not available in this system; available ports are: %s" % (com_port, str(available_coms)))
        else:
            log.info("COM OK: %s" % com_port)

        self._pipier_client_watchdog = WatchDog(suproc_command=self._pipier_client_subproc_cmd,
                                                stdin_queue=self._piper_client_stdin_queue,
                                                stdout_queue=self._piper_client_stdout_queue,
                                                parent = self)

        self._packets_processor = ReceivedPacketsProcessor(self)

        atexit.register(self.stop_client)

           # TODO:
            # 3. implement periodic checks if com is available
            #   if not: restart watchdog (can be a permanent restart; no state machine required)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def checkVPNCommand(addon):
    # Issue the openvpn command and see if the output is a bunch of commands
    if not fakeConnection():
        p = getPlatform()
        # Issue the openvpn command, expecting to get the options screen back
        if p == platforms.RPI or p == platforms.LINUX:
            # Issue Linux command
            command = getOpenVPNPath() + " > " + getVPNLogFilePath() + " &"
            if useSudo() : command = "sudo " + command
            infoTrace("platform.py", "Testing openvpn with : " + command)
            os.system(command)
        elif p == platforms.WINDOWS:
            # Issue Windows command
            command=getOpenVPNPath()
            infoTrace("platform.py", "Testing openvpn with : " + command)
            args = shlex.split(command)
            outfile = open(getVPNLogFilePath(),'w')
            proc = subprocess.Popen(args, stdout=outfile, creationflags=subprocess.SW_HIDE, shell=True)
        else:
            errorTrace("platform.py", "Unsupported platform " + str(p))

        # **** ADD MORE PLATFORMS HERE ****

        # Waiting for the log file to appear            
        xbmc.sleep(1000)
        i = 0
        while not xbmcvfs.exists(getVPNLogFilePath()) and i < 10:
            xbmc.sleep(1000)
            i = i + 1
        # If the log file appears, check it's what we expect
        if xbmcvfs.exists(getVPNLogFilePath()):
            log_file = open(getVPNLogFilePath(), 'r')
            log_file_lines = log_file.readlines()
            log_file.close()
            # Look for a phrase we'd expect to see if the call
            # worked and the list of options was displayed
            for line in log_file_lines:
                if "General Options" in line:
                    return True
            # Write the log file in case there's something in it
            errorTrace("platform.py", "Ran openvpn command and it failed")            
            writeVPNLog()
            dialog_msg = "The OpenVPN executable isn't working.  Check the log, then from a command line prompt type 'openvpn' and fix any problems reported."
        else:
            errorTrace("platform.py", "Ran openvpn command and VPN log didn't appear")
            dialog_msg = "The OpenVPN executable isn't writing out a log.  Try changing the Kodi log directory setting in Settings-Debug menu and retry."

        # Display an error message
        xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg)
        return False

    else: return True
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def isVPNTaskRunning():
    # Return True if the VPN task is still running, or the VPN connection is still active
    # Return False if the VPN task is no longer running and the connection is not active

    if fakeConnection(): return True

    p = getPlatform()
    if p == platforms.LINUX or p == platforms.RPI:
        try:
            command = "pidof openvpn"
            if useSudo() : command = "sudo " + command
            debugTrace("(Linux) Checking VPN task with " + command)
            pid = os.system(command)
            # This horrible call returns 0 if it finds a process, it's not returning the PID number
            if xbmcaddon.Addon("service.vpn.manager").getSetting("alt_pid_check") == "true":
                if pid > 0 : return True
            else:
                if pid == 0 : return True
            debugTrace("(Linux) Didn't find a running process")
            return False
        except Exception as e:
            errorTrace("platform.py", "VPN task list failed")
            errorTrace("platform.py", str(e))
            return False
    if p == platforms.WINDOWS:
        try:
            command = 'tasklist /FI "IMAGENAME eq OPENVPN.EXE"'
            debugTrace("(Windows) Checking VPN task with " + command)
            args = shlex.split(command)
            out = subprocess.check_output(args, creationflags=subprocess.SW_HIDE, shell=True).strip()
            if "openvpn.exe" in out:
                return True
            else:
                debugTrace("(Windows) Didn't find a running process")
                return False
        except Exception as e:
            errorTrace("platform.py", "VPN task list failed")
            errorTrace("platform.py", str(e))
            return False

    # **** ADD MORE PLATFORMS HERE ****

    return False
项目:vim-clangd    作者:Chilledheart    | 项目源码 | 文件源码
def StartProcess(executable_name, clangd_log_path=None):
    if not clangd_log_path or not log.logger.isEnabledFor(log.DEBUG):
        clangd_log_path = os.devnull
    fdClangd = open(clangd_log_path, 'w+')

    # fix executable file name under windows (both cygwin and native win32)
    if sys_platform == 'msys' or sys_platform == 'win32':
        if not executable_name.endswith('.exe'):
            executable_name += '.exe'

    # apply platform-specific hacks
    if sys_platform != 'win32':
        # for posix or cygwin
        fdInRead, fdInWrite = Pipe()
        fdOutRead, fdOutWrite = Pipe()
        SetCloseOnExec(fdInWrite)
        SetCloseOnExec(fdOutRead)
    else:
        # only native win32
        fdInRead, fdInWrite = Win32SocketPair()
        fdOutRead, fdOutWrite = Win32SocketPair()
    cwd = os.path.dirname(executable_name)
    # apply native win32's hack
    if sys_platform == 'win32':
        # we need hide this subprocess's window under windows, or it opens a new visible window
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        clangd = Popen(
            executable_name,
            stdin=fdInRead,
            stdout=fdOutWrite,
            stderr=fdClangd,
            cwd=cwd,
            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
            startupinfo=startupinfo)
    else:
        clangd = Popen(
            executable_name,
            stdin=fdInRead,
            stdout=fdOutWrite,
            stderr=fdClangd,
            cwd=cwd)

    return clangd, fdInWrite, fdOutRead, fdClangd