python类SW_HIDE的实例源码

PhpArrayConverter.py 文件源码 项目:SublimePhpArrayConverter 作者: gh640 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
main.py 文件源码 项目:LSP 作者: tomv564 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
node_client.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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()
wrapper_client.py 文件源码 项目:PJON-python 作者: Girgitt 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
platform.py 文件源码 项目:service.vpn.manager 作者: Zomboided 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
platform.py 文件源码 项目:service.vpn.manager 作者: Zomboided 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
rdp.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
processes.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
security.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
processes.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
languageServer.py 文件源码 项目:DXMate 作者: jtowers 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
security.py 文件源码 项目:pupy 作者: ru-faraon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
processes.py 文件源码 项目:pupy 作者: ru-faraon 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
RustFmt.py 文件源码 项目:sublime-rust-fmt 作者: Mitranim 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
speaker.py 文件源码 项目:eduActiv8 作者: imiolek-ireneusz 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
_utils.py 文件源码 项目:idascripts 作者: ctfhacker 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
main.py 文件源码 项目:PCControl 作者: renhongl 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
tools.py 文件源码 项目:EasyClangComplete 作者: niosus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:nvda-ocr 作者: nvaccess 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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"))
plugin_util.py 文件源码 项目:GoFeather 作者: frou 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:languagetool-sublime 作者: gtarawneh 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:dictationbridge-nvda 作者: dictationbridge 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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"))
util.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
interactive_shell.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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())
sidebar.py 文件源码 项目:rekit-sublime 作者: supnate 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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))
interactive_shell.py 文件源码 项目:pupy 作者: ru-faraon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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())
command_line.py 文件源码 项目:Electrify 作者: jyapayne 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()
util.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
node_client.py 文件源码 项目:sublimeTextConfig 作者: luoye-fe 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()
safe_subprocess.py 文件源码 项目:Deploy_XXNET_Server 作者: jzp820927 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号