Python subprocess.SW_HIDE Examples

The following are 30 code examples of subprocess.SW_HIDE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module subprocess , or try the search function .
Example #1
Source File: standard-format.py    From sublime-standard-format with MIT License 10 votes vote down vote up
def command_version(command):
    """
    Uses subprocess to format a given string.
    """

    startupinfo = None

    if platform == "windows":
        # Prevent cmd.exe window from popping up
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= (
            subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        )
        startupinfo.wShowWindow = subprocess.SW_HIDE

    std = subprocess.Popen(
        [command, "--version"],
        env=calculate_env(),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupinfo
    )
    out, err = std.communicate()
    return out.decode("utf-8").replace("\r", ""), err 
Example #2
Source File: server.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def _execute(self, args):
        # ugly method that should be refactored at some point
        path, args = [i.strip() for i in args.split('"') if i if not i.isspace()] if args.count('"') == 2 else [i for i in args.partition(' ') if i if not i.isspace()]
        args = [path] + args.split()
        if os.path.isfile(path):
            name = os.path.splitext(os.path.basename(path))[0]
            try:
                info = subprocess.STARTUPINFO()
                info.dwFlags = subprocess.STARTF_USESHOWWINDOW ,  subprocess.CREATE_NEW_ps_GROUP
                info.wShowWindow = subprocess.SW_HIDE
                self.child_procs[name] = subprocess.Popen(args, startupinfo=info)
                return "Running '{}' in a hidden process".format(path)
            except Exception as e:
                try:
                    self.child_procs[name] = subprocess.Popen(args, 0, None, None, subprocess.PIPE, subprocess.PIPE)
                    return "Running '{}' in a new process".format(name)
                except Exception as e:
                    util.log("{} error: {}".format(self._execute.__name__, str(e)))
        else:
            return "File '{}' not found".format(str(path)) 
Example #3
Source File: server.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def _execute(self, args):
        # ugly method that should be refactored at some point
        path, args = [i.strip() for i in args.split('"') if i if not i.isspace()] if args.count('"') == 2 else [i for i in args.partition(' ') if i if not i.isspace()]
        args = [path] + args.split()
        if os.path.isfile(path):
            name = os.path.splitext(os.path.basename(path))[0]
            try:
                info = subprocess.STARTUPINFO()
                info.dwFlags = subprocess.STARTF_USESHOWWINDOW ,  subprocess.CREATE_NEW_ps_GROUP
                info.wShowWindow = subprocess.SW_HIDE
                self.child_procs[name] = subprocess.Popen(args, startupinfo=info)
                return "Running '{}' in a hidden process".format(path)
            except Exception as e:
                try:
                    self.child_procs[name] = subprocess.Popen(args, 0, None, None, subprocess.PIPE, subprocess.PIPE)
                    return "Running '{}' in a new process".format(name)
                except Exception as e:
                    util.log("{} error: {}".format(self.execute.__name__, str(e)))
        else:
            return "File '{}' not found".format(str(path)) 
Example #4
Source File: utils.py    From mech with MIT License 6 votes vote down vote up
def tar_cmd(*args, **kwargs):
    try:
        startupinfo = None
        if os.name == "nt":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
        proc = subprocess.Popen(['tar', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
    except OSError:
        return None
    if proc.returncode:
        return None
    stdoutdata, stderrdata = map(b2s, proc.communicate())
    tar = ['tar']
    if kwargs.get('wildcards') and re.search(r'--wildcards\b', stdoutdata):
        tar.append('--wildcards')
    if kwargs.get('force_local') and re.search(r'--force-local\b', stdoutdata):
        tar.append('--force-local')
    if kwargs.get('fast_read') and sys.platform.startswith('darwin'):
        tar.append('--fast-read')
    tar.extend(args)
    return tar 
Example #5
Source File: clang_utils.py    From EasyClangComplete with MIT License 6 votes vote down vote up
def prepare_search_libclang_cmd(clang_binary, lib_file_name):
        """Prepare a command that we use to search for libclang paths."""
        stdin = None
        stdout = None
        stderr = None
        startupinfo = None
        # let's find the library
        if platform.system() == "Darwin":
            # [HACK]: wtf??? why does it not find libclang.dylib?
            get_library_path_cmd = [clang_binary, "-print-file-name="]
        elif platform.system() == "Windows":
            get_library_path_cmd = [clang_binary,
                                    "-print-prog-name=clang"]
            # Don't let console window pop-up briefly.
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            stdin = subprocess.PIPE
            stderr = subprocess.PIPE
        elif platform.system() == "Linux":
            get_library_path_cmd = [
                clang_binary, "-print-file-name={}".format(lib_file_name)]
        return get_library_path_cmd, stdin, stdout, stderr, startupinfo 
Example #6
Source File: vpnplatform.py    From service.vpn.manager with GNU General Public License v2.0 6 votes vote down vote up
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 = getKillallPath()+ " -" + 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 
Example #7
Source File: vmrun.py    From mech with MIT License 6 votes vote down vote up
def get_provider(vmrun_exe):
    """
    identifies the right hosttype for vmrun command (ws | fusion | player)
    """

    if sys.platform == 'darwin':
        return 'fusion'

    for provider in ['ws', 'player', 'fusion']:
        try:
            startupinfo = None
            if os.name == "nt":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
            proc = subprocess.Popen([vmrun_exe, '-T', provider, 'list'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
        except OSError:
            pass

        stdoutdata, stderrdata = map(b2s, proc.communicate())
        if proc.returncode == 0:
            return provider 
Example #8
Source File: QgsFmvUtils.py    From QGISFMV with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        if self.type is "ffmpeg":
            self.cmds.insert(0, ffmpeg_path)
        else:
            self.cmds.insert(0, ffprobe_path)

        qgsu.showUserAndLogMessage("", "starting Splitter on thread:" + str(threading.current_thread().ident), onlyLog=True)
        qgsu.showUserAndLogMessage("", "with args:" + ' '.join(self.cmds), onlyLog=True)

        # Hide shell windows that pops up on windows.
        if windows:
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE

        self.p = subprocess.Popen(self.cmds, startupinfo=startupinfo, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
        # Dont us _spawn here as it will DeadLock, and the splitter won't work
        #self.p = _spawn(self.cmds)
        self.nbsr = NonBlockingStreamReader(self.p)
        self.nbsr._t.join()
        qgsu.showUserAndLogMessage("", "Splitter thread ended.", onlyLog=True) 
Example #9
Source File: Backend.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _runEngineProcess(self, command_list) -> Optional[subprocess.Popen]:
        """Start the (external) backend process."""

        kwargs = {} #type: Dict[str, Any]
        if sys.platform == "win32":
            su = subprocess.STARTUPINFO()
            su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            su.wShowWindow = subprocess.SW_HIDE
            kwargs["startupinfo"] = su
            kwargs["creationflags"] = 0x00004000  # BELOW_NORMAL_PRIORITY_CLASS
        try:
            # STDIN needs to be None because we provide no input, but communicate via a local socket instead. The NUL device sometimes doesn't exist on some computers.
            # STDOUT and STDERR need to be pipes because we'd like to log the output on those channels into the application log.
            return subprocess.Popen(command_list, stdin = None, stdout = subprocess.PIPE, stderr = subprocess.PIPE, **kwargs)
        except PermissionError:
            Logger.log("e", "Couldn't start back-end: No permission to execute process.")
        except FileNotFoundError:
            Logger.logException("e", "Unable to find backend executable: %s", command_list[0])
        except BlockingIOError:
            Logger.log("e", "Couldn't start back-end: Resource is temporarily unavailable")
        except OSError as e:
            Logger.log("e", "Couldn't start back-end: Operating system is blocking it (antivirus?): {err}".format(err = str(e)))
        return None 
Example #10
Source File: process.py    From LSP with MIT License 5 votes vote down vote up
def start_server(
    server_binary_args: List[str],
    working_dir: Optional[str],
    env: Dict[str, str],
    on_stderr_log: Optional[Callable[[str], None]]
) -> Optional[subprocess.Popen]:
    si = None
    if os.name == "nt":
        server_binary_args = add_extension_if_missing(server_binary_args)
        si = subprocess.STARTUPINFO()  # type: ignore
        si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW  # type: ignore

    debug("starting " + str(server_binary_args))

    stderr_destination = subprocess.PIPE if on_stderr_log else subprocess.DEVNULL

    process = subprocess.Popen(
        server_binary_args,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=stderr_destination,
        cwd=working_dir,
        env=env,
        startupinfo=si)

    if on_stderr_log is not None:
        attach_logger(process, process.stderr, on_stderr_log)

    return process 
Example #11
Source File: payloads.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, args):
        """
        Run an executable program in a hidden process

        `Required`
        :param str path:    file path of the target program

        `Optional`
        :param str args:    arguments for the target program

        """
        log(args)
        path, args = [i.strip() for i in args.split('"') if i if not i.isspace()] if args.count('"') == 2 else [i for i in args.partition(' ') if i if not i.isspace()]
        args = [path] + args.split()
        if os.path.isfile(path):
            name = os.path.splitext(os.path.basename(path))[0]
            try:
                # attempt to run hidden process
                info = subprocess.STARTUPINFO()
                info.dwFlags = subprocess.STARTF_USESHOWWINDOW ,  subprocess.CREATE_NEW_ps_GROUP
                info.wShowWindow = subprocess.SW_HIDE
                self.execute.process_list[name] = subprocess.Popen(args, startupinfo=info)
                return "Running '{}' in a hidden process".format(path)
            except Exception as e:
                # revert to normal process if hidden process fails
                try:
                    self.execute.process_list[name] = subprocess.Popen(args, 0, None, None, subprocess.PIPE, subprocess.PIPE)
                    return "Running '{}' in a new process".format(name)
                except Exception as e:
                    log("{} error: {}".format(self.execute.__name__, str(e)))
                    return "{} error: {}".format(self.execute.__name__, str(e))
        else:
            return "File '{}' not found".format(str(path)) 
Example #12
Source File: payloads.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, args):
        """
        Run an executable program in a hidden process

        `Required`
        :param str path:    file path of the target program

        `Optional`
        :param str args:    arguments for the target program

        """
        path, args = [i.strip() for i in args.split('"') if i if not i.isspace()] if args.count('"') == 2 else [i for i in args.partition(' ') if i if not i.isspace()]
        args = [path] + args.split()
        if os.path.isfile(path):
            name = os.path.splitext(os.path.basename(path))[0]
            try:
                info = subprocess.STARTUPINFO()
                info.dwFlags = subprocess.STARTF_USESHOWWINDOW ,  subprocess.CREATE_NEW_ps_GROUP
                info.wShowWindow = subprocess.SW_HIDE
                self.execute.process_list[name] = subprocess.Popen(args, startupinfo=info)
                return "Running '{}' in a hidden process".format(path)
            except Exception as e:
                try:
                    self.execute.process_list[name] = subprocess.Popen(args, 0, None, None, subprocess.PIPE, subprocess.PIPE)
                    return "Running '{}' in a new process".format(name)
                except Exception as e:
                    log("{} error: {}".format(self.execute.__name__, str(e)))
        else:
            return "File '{}' not found".format(str(path)) 
Example #13
Source File: backend.py    From graphviz with MIT License 5 votes vote down vote up
def get_startupinfo():
        """Return subprocess.STARTUPINFO instance hiding the console window."""
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        return startupinfo 
Example #14
Source File: factory.py    From PhyloSuite with GNU General Public License v3.0 5 votes vote down vote up
def init_popen(self, commands):
        startupINFO = None
        if platform.system().lower() == "windows":
            startupINFO = subprocess.STARTUPINFO()
            startupINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupINFO.wShowWindow = subprocess.SW_HIDE
            popen = subprocess.Popen(
                commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO)
        else:
            popen = subprocess.Popen(
                commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO, shell=True,
                preexec_fn=os.setsid)
        return popen 
Example #15
Source File: Lg_Gblocks.py    From PhyloSuite with GNU General Public License v3.0 5 votes vote down vote up
def run_code(self, commands):
        startupINFO = None
        if platform.system().lower() == "windows":
            startupINFO = subprocess.STARTUPINFO()
            startupINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupINFO.wShowWindow = subprocess.SW_HIDE
            self.gb_popen = subprocess.Popen(
                commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO)
        else:
            self.gb_popen = subprocess.Popen(
                commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO,
                shell=True, preexec_fn=os.setsid)
        self.factory.emitCommands(self.logGuiSig, commands)
        is_error = False  ##判断是否出了error
        while True:
            QApplication.processEvents()
            if self.isRunning():
                try:
                    out_line = self.gb_popen.stdout.readline().decode("utf-8", errors='ignore')
                except UnicodeDecodeError:
                    out_line = self.gb_popen.stdout.readline().decode("gbk", errors='ignore')
                if out_line == "" and self.gb_popen.poll() is not None:
                    break
                self.logGuiSig.emit(out_line.strip())
                if "Execution terminated" in out_line:
                    is_error = True
            else:
                break
        if is_error:
            self.interrupt = True
            self.gblocks_exception.emit(
                "Error happened! Click <span style='font-weight:600; color:#ff0000;'>Show log</span> to see detail!")
        self.gb_popen = None 
Example #16
Source File: Lg_compareTable.py    From PhyloSuite with GNU General Public License v3.0 5 votes vote down vote up
def align(self, inputFile, outfile, mafftPath):
        # 尝试去除cmd窗口
        startupINFO = None
        if platform.system().lower() == "windows":
            startupINFO = subprocess.STARTUPINFO()
            startupINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupINFO.wShowWindow = subprocess.SW_HIDE
        ch_out = ' --inputorder '
        strategy = ' --auto'
        arg = ""
        commands = mafftPath + arg + strategy + ch_out + '"' + inputFile  + \
            '"' + ' > ' + '"' + outfile + '"'
        self.mafft_popen = subprocess.Popen(
            commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO, shell=True)
        self.run_command(commands, self.mafft_popen) 
Example #17
Source File: Lg_HmmCleaner.py    From PhyloSuite with GNU General Public License v3.0 5 votes vote down vote up
def run(dict_args, command, file):
    fileBase = os.path.basename(file)
    inputFile = " \"%s\"" % file
    command = command.replace(" $alignment$", inputFile) #html输出替换名字
    startupINFO = None
    if platform.system().lower() == "windows":
        startupINFO = subprocess.STARTUPINFO()
        startupINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupINFO.wShowWindow = subprocess.SW_HIDE
        popen = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO)
    else:
        popen = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupINFO, shell=True,
            preexec_fn=os.setsid)
    run.queue.put(("popen", popen.pid))
    # 存log文件
    with open(file + ".log", "a", encoding="utf-8") as log_file:
        run.queue.put(("log", "%sCommands%s\n%s\n%s" % ("=" * 45, "=" * 45, command, "=" * 98)))
        is_error = False
        while True:
            try:
                out_line = popen.stdout.readline().decode("utf-8", errors='ignore')
            except UnicodeDecodeError:
                out_line = popen.stdout.readline().decode("gbk", errors='ignore')
            if out_line == "" and popen.poll() is not None:
                break
            if re.search(r"\S+", out_line):
                log_file.write(out_line)
                run.queue.put(("log", fileBase + " --- " + out_line.strip()))
            if re.search(r"ERROR", out_line):
                run.queue.put(("log", fileBase + " --- " + out_line.strip()))
                is_error = True
        if is_error:
            run.queue.put(("error",))
        else:
            pass
        run.queue.put(("prog", "finished"))
        run.queue.put(("log", fileBase + " --- " + "Done!"))
        run.queue.put(("popen finished", popen.pid))
    return "finished" 
Example #18
Source File: cudax_nodejs.py    From CudaText with Mozilla Public License 2.0 5 votes vote down vote up
def run_node(text, params_list):
    enc = 'utf8'
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        try:
            p = subprocess.Popen([NODE_FILE] + params_list, 
              startupinfo=startupinfo, 
              stdout=subprocess.PIPE, 
              stdin=subprocess.PIPE, 
              stderr=subprocess.PIPE)
        except OSError:
            raise Exception(MSG_CANNOT_RUN_NODE)
    else:
        try:
            p = subprocess.Popen([NODE_FILE] + params_list, 
              stdout=subprocess.PIPE, 
              stdin=subprocess.PIPE, 
              stderr=subprocess.PIPE)
        except OSError:
            raise Exception(MSG_CANNOT_RUN_NODE)
    

    stdout, stderr = p.communicate(text.encode(enc))
    if stdout:
        return stdout.decode(enc)
    else:
        raise Exception('Error:\n' + stderr.decode(enc)) 
Example #19
Source File: util.py    From st3-gitblame with MIT License 5 votes vote down vote up
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 
Example #20
Source File: Communicator.py    From wotmods with GNU General Public License v2.0 5 votes vote down vote up
def __runTask(self):
        element = self.queue.top()
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        proc = subprocess.Popen(element[1], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
        t = threading.Thread(target=partial(self.__elaborate, element[0], proc, element[2]))
        t.start() 
Example #21
Source File: Communicator.py    From wotmods with GNU General Public License v2.0 5 votes vote down vote up
def addFreeRequest(self, command, message, callback):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
        t = threading.Thread(target=partial(self.__elaborate, callback, proc, message))
        t.start() 
Example #22
Source File: SixthSenseDuration.py    From wotmods with GNU General Public License v2.0 5 votes vote down vote up
def threadedPlayExtSound():
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        subprocess.Popen(SixthSenseDuration.myConf['AudioExternal'], startupinfo=startupinfo) 
Example #23
Source File: FrontEnd.py    From wotmods with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, service):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        self.process = subprocess.Popen(service, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=False, startupinfo=startupinfo)
        self.stdin = self.process.stdin
        self.stdout = NBSR(self.process.stdout, self.process.stderr) 
Example #24
Source File: tools.py    From EasyClangComplete with MIT License 5 votes vote down vote up
def run_command(command, shell=False, cwd=path.curdir, env=environ,
                    stdin=None, default=None):
        """Run a generic command in a subprocess.

        Args:
            command (str): command to run
            stdin: The standard input channel for the started process.
            default (andy): The default return value in case run fails.

        Returns:
            str: raw command output or default value
        """
        output_text = default
        try:
            startupinfo = None
            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
                if stdin is None:
                    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)
        except OSError:
            _log.debug(
                "Executable file not found executing: {}".format(command))
        return output_text 
Example #25
Source File: utils.py    From qgis-processing-r with GNU General Public License v3.0 5 votes vote down vote up
def get_process_startup_info():
        """
        Returns the correct startup info to use when calling commands for different platforms
        """
        # For MS-Windows, we need to hide the console window.
        si = None
        if RUtils.is_windows():
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            si.wShowWindow = subprocess.SW_HIDE
        return si 
Example #26
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def StartProcess(*args):
    #SetIndent(1)
    startupInfo = subprocess.STARTUPINFO()
    startupInfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
    startupInfo.wShowWindow = subprocess.SW_HIDE
    process = Popen(
        args,
        cwd=EncodePath(join(builder.buildSetup.buildDir)),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupInfo,
    )
    while process.returncode is None:
        process.poll()
        errData = process.recv_err()
        if errData is not None:
            sys.stderr.write(errData)
        inData = process.recv()
        if inData is not None:
            if inData:
                sys.stdout.write(inData)
            else:
                time.sleep(0.1)
        else:
            break
    process.wait()
    #SetIndent(0)
    return process.returncode 
Example #27
Source File: processes.py    From backdoorme with MIT License 5 votes vote down vote up
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 
Example #28
Source File: color_trace_multi.py    From color_trace with GNU General Public License v2.0 5 votes vote down vote up
def process_command(command, stdinput=None, stdout_=False, stderr_=False):
    """run command in invisible shell, return stdout and/or stderr as specified

    Returns stdout, stderr, or a tuple (stdout, stderr) depending on which of
    stdout_ and stderr_ is True. Raises an exception if the command encounters
    an error.

    command: command with arguments to send to command line
    stdinput: data (bytes) to send to command's stdin, or None
    stdout_: True to receive command's stdout in the return value
    stderr_: True to receive command's stderr in the return value
"""
    verbose(command)
    stdin_pipe   = (subprocess.PIPE if stdinput  is not None else None)
    stdout_pipe  = (subprocess.PIPE if stdout_ is True else None)
    stderr_pipe  = subprocess.PIPE

    #process = subprocess.Popen(command, stdin=stdin_pipe, stderr=stderr_pipe, stdout=stdout_pipe,
        #shell=True, creationflags=subprocess.SW_HIDE)
    process = subprocess.Popen(command, stdin=stdin_pipe, stderr=stderr_pipe, stdout=stdout_pipe,
        shell=True)

    stdoutput, stderror = process.communicate(stdinput)
    #print(stderror)
    returncode = process.wait()
    if returncode != 0:
        Exception(stderror.decode())
    if stdout_ and not stderr_:
        return stdoutput
    elif stderr_ and not stdout_:
        return stderr
    elif stdout_ and stderr_:
        return (stdoutput, stderror)
    elif not stdout_ and not stderr_:
        return None 
Example #29
Source File: latextext.py    From LaTeXText with GNU General Public License v3.0 5 votes vote down vote up
def _exec_command(self, cmd, ok_return_value=0):
        """
        Run given command, check return value, and return
        concatenated stdout and stderr.
        :param cmd: Command to execute
        :param ok_return_value: The expected return value after successful completion
        """

        try:
            # hides the command window for cli tools that are run (in Windows)
            info = None
            if PLATFORM == WINDOWS:
                info = subprocess.STARTUPINFO()
                info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                info.wShowWindow = subprocess.SW_HIDE

            p = subprocess.Popen(cmd,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 stdin=subprocess.PIPE,
                                 startupinfo=info)
            out, err = p.communicate()
        except OSError as err:
            log_error("\nCommand \"%s\" > failed: %s" % (' '.join(cmd), err))
            raise RuntimeError()

        if ok_return_value is not None and p.returncode != ok_return_value:
            log_error("\nCommand \"%s\" failed (code %d): \n\n %s" % (' '.join(cmd), p.returncode, out + err))
            raise RuntimeError()
        return out + err

    # render given latex code and return the result as an SVG group element 
Example #30
Source File: utility.py    From textext with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exec_command(cmd, ok_return_value=0):
    """
    Run given command, check return value, and return
    concatenated stdout and stderr.
    :param cmd: Command to execute
    :param ok_return_value: The expected return value after successful completion
    :raises: TexTextCommandNotFound, TexTextCommandFailed
    """

    try:
        # hides the command window for cli tools that are run (in Windows)
        info = None
        if PLATFORM == WINDOWS:
            info = subprocess.STARTUPINFO()
            info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            info.wShowWindow = subprocess.SW_HIDE

        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             startupinfo=info)
        out, err = p.communicate()
    except OSError as err:
        raise TexTextCommandNotFound("Command %s failed: %s" % (' '.join(cmd), err))

    if ok_return_value is not None and p.returncode != ok_return_value:
        raise TexTextCommandFailed(message="Command %s failed (code %d)" % (' '.join(cmd), p.returncode),
                                   return_code=p.returncode,
                                   stdout=out,
                                   stderr=err)
    return out + err