Python subprocess.STARTUPINFO Examples

The following are 30 code examples for showing how to use subprocess.STARTUPINFO(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module subprocess , or try the search function .

Example 1
Project: sublime-GitConflictResolver   Author: sascha-wolf   File: util.py    License: MIT License 6 votes vote down vote up
def execute_command(command, working_dir=None):
    startupinfo = None
    # hide console window on windows
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    output = None
    try:
        output = subprocess.check_output(
            command,
            cwd=working_dir,
            startupinfo=startupinfo
        )
    except (subprocess.CalledProcessError, AttributeError):
        # Git will return an error when the given directory
        # is not a repository, which means that we can ignore this error
        pass
    else:
        output = str(output, encoding="utf-8").strip()

    return output 
Example 2
Project: Radium   Author: mehulj94   File: Radiumkeylogger.py    License: Apache License 2.0 6 votes vote down vote up
def subprocess_args(include_stdout=True):
    if hasattr(subprocess, 'STARTUPINFO'):
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        env = os.environ
    else:
        si = None
        env = None

    if include_stdout:
        ret = {'stdout:': subprocess.PIPE}
    else:
        ret = {}

    ret.update({'stdin': subprocess.PIPE,
                'stderr': subprocess.PIPE,
                'startupinfo': si,
                'env': env })
    return ret

#Function to get the Process ID 
Example 3
Project: pyspelling   Author: facelessuser   File: __init__.py    License: MIT License 6 votes vote down vote up
def get_process(cmd):
    """Get a command process."""

    if sys.platform.startswith('win'):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        process = subprocess.Popen(
            cmd,
            startupinfo=startupinfo,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            stdin=subprocess.PIPE,
            shell=False
        )
    else:
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            stdin=subprocess.PIPE,
            shell=False
        )
    return process 
Example 4
Project: imageio-ffmpeg   Author: imageio   File: _utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _popen_kwargs(prevent_sigint=False):
    startupinfo = None
    preexec_fn = None
    creationflags = 0
    if sys.platform.startswith("win"):
        # Stops executable from flashing on Windows (see #22)
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    if prevent_sigint:
        # Prevent propagation of sigint (see #4)
        # https://stackoverflow.com/questions/5045771
        if sys.platform.startswith("win"):
            creationflags = 0x00000200
        else:
            preexec_fn = os.setpgrp  # the _pre_exec does not seem to work
    return {
        "startupinfo": startupinfo,
        "creationflags": creationflags,
        "preexec_fn": preexec_fn,
    } 
Example 5
Project: sublime-standard-format   Author: bcomnes   File: standard-format.py    License: MIT License 6 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 6
Project: cryptolens-python   Author: Cryptolens   File: internal.py    License: MIT License 6 votes vote down vote up
def subprocess_args(include_stdout=True):
    if hasattr(subprocess, 'STARTUPINFO'):
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        env = os.environ
    else:
        si = None
        env = None

    if include_stdout:
        ret = {'stdout': subprocess.PIPE}
    else:
        ret = {}

    ret.update({'stdin': subprocess.PIPE,
                'stderr': subprocess.PIPE,
                'startupinfo': si,
                'env': env })
    return ret 
Example 7
Project: kano-burners   Author: KanoComputing   File: aria2_downloader.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, url, dest, progress_bar=False):
        self.url = url
        self.dest = dest
        self.hash_type = None
        self.hash_value = None
        self.process = None
        self.secret = ''.join(format(ord(x), 'x') for x in os.urandom(10))
        self.gid = 'DEADC0D9BEEFFACE'

        self.status = None
        self.failed = False
        self.failure = None

        self.ariaStatus = {}
        self.gid = None
        if platform.system()=='Darwin':
            self.aria_stdout = None
            self.startupinfo = None
        else:
            self.aria_stdout = None
            self.startupinfo = subprocess.STARTUPINFO()
            self.startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            self.startupinfo.wShowWindow = subprocess.SW_HIDE 
Example 8
Project: adbutils   Author: openatx   File: _utils.py    License: MIT License 6 votes vote down vote up
def _popen_kwargs(prevent_sigint=False):
    startupinfo = None
    preexec_fn = None
    creationflags = 0
    if sys.platform.startswith("win"):
        # Stops executable from flashing on Windows (see imageio/imageio-ffmpeg#22)
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    if prevent_sigint:
        # Prevent propagation of sigint (see imageio/imageio-ffmpeg#4)
        # https://stackoverflow.com/questions/5045771
        if sys.platform.startswith("win"):
            creationflags = 0x00000200
        else:
            preexec_fn = os.setpgrp  # the _pre_exec does not seem to work
    return {
        "startupinfo": startupinfo,
        "creationflags": creationflags,
        "preexec_fn": preexec_fn,
    } 
Example 9
Project: CityEnergyAnalyst   Author: architecture-building-systems   File: ghhelper.py    License: MIT License 6 votes vote down vote up
def run_cli(script_name, **parameters):
    """Run the CLI in a subprocess without showing windows"""
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    command = [get_python_exe(), '-u', '-m', 'cea.interfaces.cli.cli', script_name]
    for parameter_name, parameter_value in parameters.items():
        parameter_name = parameter_name.replace('_', '-')
        command.append('--' + parameter_name)
        command.append(str(parameter_value))
    print('Executing: ' + ' '.join(command))
    process = subprocess.Popen(command, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               cwd=tempfile.gettempdir())
    while True:
        next_line = process.stdout.readline()
        if next_line == '' and process.poll() is not None:
            break
        print(next_line.rstrip())
    stdout, stderr = process.communicate()
    print(stdout)
    print(stderr)
    if process.returncode != 0:
        raise Exception('Tool did not run successfully') 
Example 10
Project: sublime_debugger   Author: daveleroy   File: transports.py    License: MIT License 6 votes vote down vote up
def __init__(self, command: List[str], cwd: Optional[str]):
		# taken from Default/exec.py
		# Hide the console window on Windows
		startupinfo = None
		if os.name == "nt":
			startupinfo = subprocess.STARTUPINFO() #type: ignore
			startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW #type: ignore

		super().__init__(command,
			stdout=subprocess.PIPE,
			stderr=subprocess.PIPE,
			stdin=subprocess.PIPE,
			shell=False,
			bufsize=0,
			startupinfo=startupinfo,
			cwd = cwd)

		self.closed = False 
Example 11
Project: Uranium   Author: Ultimaker   File: Backend.py    License: 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 12
Project: RunInIndesign   Author: vamitul   File: runInIndesign.py    License: MIT License 6 votes vote down vote up
def __init__(self, shell_cmd):
		if not shell_cmd:
			raise ValueError("shell_cmd is required")

		if shell_cmd and not isinstance(shell_cmd, str):
			raise ValueError("shell_cmd must be a string")

		self.killed = False

		# Hide the console window on Windows
		startupinfo = None
		if os.name == "nt":
			startupinfo = subprocess.STARTUPINFO()
			#startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

	   
		print (shell_cmd)
		if sys.platform == "win32":
			# Use shell=True on Windows, so shell_cmd is passed through with the correct escaping
			self.proc = subprocess.Popen(shell_cmd, startupinfo=startupinfo, shell=True)
		elif shell_cmd and sys.platform == "darwin":
			# Use a login shell on OSX, otherwise the users expected env vars won't be setup
			self.proc = subprocess.Popen(["/bin/bash", "-l", "-c", shell_cmd], startupinfo=startupinfo, shell=False)

		self.proc.wait() 
Example 13
Project: QGISFMV   Author: All4Gis   File: QgsFmvUtils.py    License: 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 14
Project: MR   Author: bkerler   File: fs_whatsapp.py    License: MIT License 6 votes vote down vote up
def run(cmd):
    if sys.platform == 'win32':
      startupinfo = subprocess.STARTUPINFO()
      startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    else:
      startupinfo = None
    p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo)
    #logtext.insert(END, "Cmd>")
    #for s in cmd:
    #    logtext.insert(END, " " + s)
    #logtext.insert(END, "\r\n")
    stdout = ''
    while True:
        line = str(p.stdout.readline(), encoding='UTF-8')
        stdout += line
        #logtext.insert(END, line)
        #logtext.yview(END)
        curstat = p.poll()
        if ((line == '') and (curstat != None)):
            break
    return stdout 
Example 15
Project: mech   Author: mechboxes   File: vmrun.py    License: 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 16
Project: ncm2   Author: ncm2   File: ncm2.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **keys):
            if 'startupinfo' not in keys:
                si = subprocess.STARTUPINFO()
                si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                keys['startupinfo'] = si
            cls.__init__(self, *args, **keys) 
Example 17
Project: gphotos-sync   Author: gilesknap   File: Main.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kargs):
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            kargs["startupinfo"] = startupinfo
            super().__init__(*args, **kargs) 
Example 18
def start(**kwargs):
    torrent2http_dir, torrent2http_bin = get_torrent2http_binary()
    args = [torrent2http_bin]
    bind_port = find_free_port()
    kwargs["bind"] = ":%d" % bind_port

    for k, v in kwargs.items():
        args.append("--%s" % k)
        if v:
            args.append(v)

    # Needed because torrent2http is vendored with Boost and libtorrent-rasterbar
    env = os.environ.copy()
    env["LD_LIBRARY_PATH"] = torrent2http_dir
    env["DYLD_LIBRARY_PATH"] = torrent2http_dir

    import xbmc
    xbmc.log(repr(args))
    kwargs = {
        "cwd": torrent2http_dir,
        "env": env,
    }
    if sys.platform == "win32":
        si = subprocess.STARTUPINFO()
        si.dwFlags |= 1
        si.wShowWindow = 0
        kwargs["startupinfo"] = si
    proc = subprocess.Popen(args, **kwargs)
    proc.bind_address = "localhost:%d" % bind_port
    def proc_close():
        if not proc.poll():
            plugin.log.info("Trying to stop torrent2http at http://%s/shutdown" % proc.bind_address)
            try:
                url_get("http://%s/shutdown" % proc.bind_address, with_immunicity=False)
                proc.wait()
            except Exception, e:
                plugin.log.info('Failed to sto torrent2http')
                map(plugin.log.info, traceback.format_exc(e).split('\n')) 
Example 19
Project: honeybee   Author: ladybug-tools   File: pyrad_proc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __configure_subprocess(self):
        '''Prevent subprocess module failure in frozen scripts on Windows.
           Prevent console windows from popping up when not console based.
           Make sure we use the version-specific string types.
        '''
        # On Windows, sys.stdxxx may not be available when:
        # - built as *.exe with "pyinstaller --noconsole"
        # - invoked via CreateProcess() and stream not redirected
        try:
            sys.__stdin__.fileno()
            self._stdin = sys.stdin
        except BaseException:
            self._stdin = PIPE
        try:
            sys.__stdout__.fileno()
            self._stdout = sys.stdout
        except BaseException:
            self._stdout = PIPE
        try:
            sys.__stderr__.fileno()
            self._stderr = sys.stderr
        # keep subprocesses from opening their own console.
        except BaseException:
            self._stderr = PIPE
        if hasattr(subprocess, 'STARTUPINFO'):
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self._pipeargs = {'startupinfo': si}
        else:
            self._pipeargs = {}
        # type names vary between Py2.7 and 3.x
        self._strtypes = (type(b''), type(u'')) 
Example 20
Project: rclonesync-V2   Author: cjnaz   File: win_subprocess.py    License: MIT License 5 votes vote down vote up
def _execute_child(self, args, executable, preexec_fn, close_fds,
                       cwd, env, universal_newlines,
                       startupinfo, creationflags, shell, to_close,
                       p2cread, p2cwrite,
                       c2pread, c2pwrite,
                       errread, errwrite):
        """Code from part of _execute_child from Python 2.7 (9fbb65e)
        There are only 2 little changes concerning the construction of
        the the final string in shell mode: we preempt the creation of
        the command string when shell is True, because original function
        will try to encode unicode args which we want to avoid to be able to
        sending it as-is to ``CreateProcess``.
        """
        if not isinstance(args, subprocess.types.StringTypes):
            args = subprocess.list2cmdline(args)

        if startupinfo is None:
            startupinfo = subprocess.STARTUPINFO()
        if shell:
            startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = _subprocess.SW_HIDE
            comspec = os.environ.get("COMSPEC", unicode("cmd.exe"))
            args = unicode('{} /c "{}"').format(comspec, args)
            if (_subprocess.GetVersion() >= 0x80000000 or
                    os.path.basename(comspec).lower() == "command.com"):
                w9xpopen = self._find_w9xpopen()
                args = unicode('"%s" %s') % (w9xpopen, args)
                creationflags |= _subprocess.CREATE_NEW_CONSOLE

        super(Popen, self)._execute_child(args, executable,
            preexec_fn, close_fds, cwd, env, universal_newlines,
            startupinfo, creationflags, False, to_close, p2cread,
            p2cwrite, c2pread, c2pwrite, errread, errwrite) 
Example 21
Project: king-phisher   Author: rsmusllp   File: startup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_process(process_args, wait=True, cwd=None):
	"""
	Start a subprocess and optionally wait for it to finish. If not **wait**, a
	handle to the subprocess is returned instead of ``True`` when it exits
	successfully. This function differs from :py:func:`.run_process` in that it
	optionally waits for the subprocess to finish, and can return a handle to
	it.

	:param tuple process_args: The arguments for the processes including the binary.
	:param bool wait: Whether or not to wait for the subprocess to finish before returning.
	:param str cwd: The optional current working directory.
	:return: If **wait** is set to True, then a boolean indication success is returned, else a handle to the subprocess is returened.
	"""
	cwd = cwd or os.getcwd()
	if isinstance(process_args, str):
		process_args = shlex.split(process_args)
	close_fds = True
	startupinfo = None
	preexec_fn = None if wait else getattr(os, 'setsid', None)
	if sys.platform.startswith('win'):
		close_fds = False
		startupinfo = subprocess.STARTUPINFO()
		startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		startupinfo.wShowWindow = subprocess.SW_HIDE

	logger = logging.getLogger('KingPhisher.ExternalProcess')
	logger.debug('starting external process: ' + ' '.join(process_args))
	proc_h = subprocess.Popen(
		process_args,
		stdin=subprocess.PIPE,
		stdout=subprocess.PIPE,
		stderr=subprocess.PIPE,
		preexec_fn=preexec_fn,
		close_fds=close_fds,
		cwd=cwd,
		startupinfo=startupinfo
	)
	if not wait:
		return proc_h
	return proc_h.wait() == 0 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_subprocess.py    License: Apache License 2.0 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 23
Project: D-VAE   Author: muhanzhang   File: windows.py    License: MIT License 5 votes vote down vote up
def subprocess_Popen(command, **params):
    """
    Utility function to work around windows behavior that open windows.

    :see: call_subprocess_Popen and output_subprocess_Popen
    """
    startupinfo = None
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        try:
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        except AttributeError:
            startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW

        # Anaconda for Windows does not always provide .exe files
        # in the PATH, they also have .bat files that call the corresponding
        # executable. For instance, "g++.bat" is in the PATH, not "g++.exe"
        # Unless "shell=True", "g++.bat" is not executed when trying to
        # execute "g++" without extensions.
        # (Executing "g++.bat" explicitly would also work.)
        params['shell'] = True

    # Using the dummy file descriptors below is a workaround for a
    # crash experienced in an unusual Python 2.4.4 Windows environment
    # with the default None values.
    stdin = None
    if "stdin" not in params:
        stdin = open(os.devnull)
        params['stdin'] = stdin.fileno()

    try:
        proc = subprocess.Popen(command, startupinfo=startupinfo, **params)
    finally:
        if stdin is not None:
            del stdin
    return proc 
Example 24
Project: Grok-backdoor   Author: deepzec   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def launchTunnelWithoutConsole(command, port):
    """Launches 'command' windowless and waits until finished"""
#    startupinfo = subprocess.STARTUPINFO()
#    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#    startupinfo.wShowWindow = subprocess.SW_HIDE
#    subprocess.Popen([command, 'tcp', port], startupinfo=startupinfo)
    if ostype == 'windows':
        os.popen2('START /B '+command+' tcp '+port)

    else:
        os.popen2(command+' tcp '+port + ' &') 
Example 25
Project: sublime-standard-format   Author: bcomnes   File: standard-format.py    License: MIT License 5 votes vote down vote up
def standard_format(string, 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,
        env=calculate_env(),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupinfo
    )

    std.stdin.write(bytes(string, 'UTF-8'))
    out, err = std.communicate()
    print(err)
    return out.decode("utf-8"), None 
Example 26
Project: BinderFilter   Author: dxwu   File: test_subprocess.py    License: MIT License 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 27
Project: textext   Author: textext   File: win_app_paths.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_cmd_in_syspath(command_name):
    """
    Checks if command_name can be executed without throwing FileNotFoundError.
    If the command could be executed True is returned, otherwise False.

    (Currently not used, but might be useful in the future...)
    """
    try:
        info = _sp.STARTUPINFO()
        info.dwFlags |= _sp.STARTF_USESHOWWINDOW
        info.wShowWindow = _sp.SW_HIDE

        proc = _sp.Popen([command_name, "--help"], stdout=_sp.PIPE, stderr=_sp.PIPE, stdin=_sp.PIPE, startupinfo=info)
        _, _ = proc.communicate()
        return True
    except WindowsError as excpt:
        return False 
Example 28
Project: textext   Author: textext   File: requirements_check.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def call_command(command, return_code=0): # type: (List,Optional[int]) -> Tuple[str, str]
        # Ensure that command window does not pop up on Windows!
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = subprocess.SW_HIDE
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=info)
        stdout, stderr = p.communicate()
        if return_code is not None and p.returncode != return_code:
            raise subprocess.CalledProcessError(p.returncode, command)
        return stdout, stderr 
Example 29
Project: textext   Author: textext   File: utility.py    License: 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 
Example 30
Project: pipeline   Author: liorbenhorin   File: email.py    License: MIT License 5 votes vote down vote up
def _invoke(self, cmdline):
        if sys.platform[:3] == 'win':
            closefds = False
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        else:
            closefds = True
            startupinfo = None

        if (os.environ.get('DISPLAY') or sys.platform[:3] == 'win' or
                                                    sys.platform == 'darwin'):
            inout = file(os.devnull, 'r+')
        else:
            # for TTY programs, we need stdin/out
            inout = None

        # if possible, put the child precess in separate process group,
        # so keyboard interrupts don't affect child precess as well as
        # Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)

        pipe = subprocess.Popen(cmdline, stdin=inout, stdout=inout,
                                stderr=inout, close_fds=closefds,
                                preexec_fn=setsid, startupinfo=startupinfo)

        # It is assumed that this kind of tools (gnome-open, kfmclient,
        # exo-open, xdg-open and open for OSX) immediately exit after lauching
        # the specific application
        returncode = pipe.wait()
        if hasattr(self, 'fixreturncode'):
            returncode = self.fixreturncode(returncode)
        return not returncode