Python subprocess.SW_HIDE Examples

The following are 30 code examples for showing how to use subprocess.SW_HIDE(). 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-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 2
Project: service.vpn.manager   Author: Zomboided   File: vpnplatform.py    License: 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 3
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 4
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 5
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 6
Project: mech   Author: mechboxes   File: utils.py    License: 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 7
Project: byob   Author: malwaredllc   File: server.py    License: 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 8
Project: byob   Author: malwaredllc   File: server.py    License: 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 9
Project: EasyClangComplete   Author: niosus   File: clang_utils.py    License: 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 10
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 11
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 12
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 13
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 14
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 15
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 16
Project: FATE   Author: FederatedAI   File: job_utils.py    License: Apache License 2.0 5 votes vote down vote up
def run_subprocess(config_dir, process_cmd, log_dir=None):
    stat_logger.info('Starting process command: {}'.format(process_cmd))
    stat_logger.info(' '.join(process_cmd))

    os.makedirs(config_dir, exist_ok=True)
    if log_dir:
        os.makedirs(log_dir, exist_ok=True)
    std_log = open(os.path.join(log_dir if log_dir else config_dir, 'std.log'), 'w')
    pid_path = os.path.join(config_dir, 'pid')

    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
    else:
        startupinfo = None
    p = subprocess.Popen(process_cmd,
                         stdout=std_log,
                         stderr=std_log,
                         startupinfo=startupinfo
                         )
    with open(pid_path, 'w') as f:
        f.truncate()
        f.write(str(p.pid) + "\n")
        f.flush()
    return p 
Example 17
Project: NoobSec-Toolkit   Author: krintoxi   File: processes.py    License: 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 18
Project: NoobSec-Toolkit   Author: krintoxi   File: processes.py    License: 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 19
Project: sublime-import-helper   Author: unlight   File: exec_command.py    License: MIT License 5 votes vote down vote up
def exec(cmd, input):
    if os.name == "nt":
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
        proc = subprocess.Popen(
            cmd,
            cwd=PACKAGE_PATH,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            startupinfo=si,
        )
    else:
        proc = subprocess.Popen(
            cmd,
            cwd=PACKAGE_PATH,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    if type(input) == str:
        input = input.encode()
    outs, errs = proc.communicate(input=input)
    err = errs.decode().strip()
    if bool(err):
        debug("Exec error", err, True)
    return (err, outs.decode().strip()) 
Example 20
Project: eduActiv8   Author: imiolek-ireneusz   File: speaker.py    License: 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 21
Project: LaTeXText   Author: seebk   File: latextext.py    License: 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 22
Project: anima   Author: eoyilmaz   File: repr_tools.py    License: MIT License 5 votes vote down vote up
def make_tx(self, texture_path):
        """converts the given texture to TX
        """
        # check if it is tiled
        tile_path = texture_path
        orig_path_as_tx = ''.join([os.path.splitext(texture_path)[0], '.tx'])

        if '<' in tile_path:
            # replace any <U> and <V> with an *
            tile_path = tile_path.replace('<U>', '*')
            tile_path = tile_path.replace('<V>', '*')
            tile_path = tile_path.replace('<UDIM>', '*')

        import glob
        files_to_process = glob.glob(tile_path)

        for tile_path in files_to_process:
            tx_path = ''.join([os.path.splitext(tile_path)[0], '.tx'])
            # generate if not exists
            if not os.path.exists(tx_path):
                # TODO: Consider Color Management
                cmd = 'maketx -o "%s" -u --oiio %s' % (tx_path, tile_path)

                if os.name == 'nt':
                    proc = subprocess.Popen(
                        cmd,
                        creationflags=subprocess.SW_HIDE,
                        shell=True
                    )
                else:
                    proc = subprocess.Popen(
                        cmd,
                        shell=True
                    )
    
                proc.wait()

        return orig_path_as_tx 
Example 23
Project: anima   Author: eoyilmaz   File: redshift.py    License: MIT License 5 votes vote down vote up
def convert(self):
        """converts the given input_file to an rstexbin
        """
        processed_files = []

        import subprocess
        from anima.ui.progress_dialog import ProgressDialogManager
        pdm = ProgressDialogManager()
        caller = pdm.register(
            len(self.files_to_process),
            title='Converting Textures'
        )
        for file_path in self.files_to_process:
            command = '%s "%s"' % (self.executable, file_path)
            rsmap_full_path = \
                '%s.rstexbin' % os.path.splitext(file_path)[0]

            # os.system(command)
            if os.name == 'nt':
                proc = subprocess.Popen(
                    command,
                    creationflags=subprocess.SW_HIDE,
                    shell=True
                )
            else:
                proc = subprocess.Popen(
                    command,
                    shell=True
                )
            proc.wait()

            processed_files.append(rsmap_full_path)
            caller.step()
        caller.end_progress()

        return processed_files 
Example 24
Project: mech   Author: mechboxes   File: utils.py    License: MIT License 5 votes vote down vote up
def init_box(name, version, force=False, save=True, requests_kwargs={}):
    if not locate('.mech', '*.vmx'):
        name_version_box = add_box(name, name=name, version=version, force=force, save=save, requests_kwargs=requests_kwargs)
        if not name_version_box:
            puts_err(colored.red("Cannot find a valid box with a VMX file in it"))
            sys.exit(1)
        name, version, box = name_version_box
        # box = locate(os.path.join(*filter(None, (HOME, 'boxes', name, version))), '*.box')

        puts_err(colored.blue("Extracting box '{}'...".format(name)))
        makedirs('.mech')
        if sys.platform == 'win32':
            cmd = tar_cmd('-xf', box, force_local=True)
        else:
            cmd = tar_cmd('-xf', box)
        if cmd:
            startupinfo = None
            if os.name == "nt":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
            proc = subprocess.Popen(cmd, cwd='.mech', startupinfo=startupinfo)
            if proc.wait():
                puts_err(colored.red("Cannot extract box"))
                sys.exit(1)
        else:
            tar = tarfile.open(box, 'r')
            tar.extractall('.mech')

        if not save and box.startswith(tempfile.gettempdir()):
            os.unlink(box)

    vmx = get_vmx()

    update_vmx(vmx)

    return vmx 
Example 25
Project: mech   Author: mechboxes   File: utils.py    License: MIT License 5 votes vote down vote up
def add_box_file(name, version, filename, url=None, force=False, save=True):
    puts_err(colored.blue("Checking box '{}' integrity...".format(name)))

    if sys.platform == 'win32':
        cmd = tar_cmd('-tf', filename, '*.vmx', wildcards=True, fast_read=True, force_local=True)
    else:
        cmd = tar_cmd('-tf', filename, '*.vmx', wildcards=True, fast_read=True)
    if cmd:
        startupinfo = None
        if os.name == "nt":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
        proc = subprocess.Popen(cmd, startupinfo=startupinfo)
        valid_tar = not proc.wait()
    else:
        tar = tarfile.open(filename, 'r')
        files = tar.getnames()
        valid_tar = False
        for i in files:
            if i.endswith('vmx'):
                valid_tar = True
                break
            if i.startswith('/') or i.startswith('..'):
                puts_err(colored.red(textwrap.fill(
                    "This box is comprised of filenames starting with '/' or '..' "
                    "Exiting for the safety of your files."
                )))
                sys.exit(1)

    if valid_tar:
        if save:
            boxname = os.path.basename(url if url else filename)
            box = os.path.join(*filter(None, (HOME, 'boxes', name, version, boxname)))
            path = os.path.dirname(box)
            makedirs(path)
            if not os.path.exists(box) or force:
                copyfile(filename, box)
        else:
            box = filename
        return name, version, box 
Example 26
Project: CudaText   Author: Alexey-T   File: cudax_nodejs.py    License: 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 27
Project: CudaText   Author: Alexey-T   File: cudax_nodejs.py    License: 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 28
Project: byob   Author: malwaredllc   File: payloads.py    License: 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 29
Project: byob   Author: malwaredllc   File: payloads.py    License: 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 30
Project: graphviz   Author: xflr6   File: backend.py    License: 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