Python subprocess.CREATE_NEW_CONSOLE Examples

The following are 27 code examples of subprocess.CREATE_NEW_CONSOLE(). 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: 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 #2
Source File: aws.py    From shimit with GNU General Public License v3.0 6 votes vote down vote up
def apply_cli_session(cls, creds, region):
        ''' Applies the given credentials (i.e. AccessKey, SecretAccessKey and SessionToken) to a new shell to use with aws cli.
            The credentials are used as environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_DEFAULT_REGION
            that aws cli uses.
            The region is the desired region to connect to (e.g. us-east-1).
            :param : boto3 returned credentials dict
            :param region: aws region to connect to
        '''
        # Set up environment for opening shell with credentials
        os.environ["AWS_ACCESS_KEY_ID"] = creds["AccessKeyId"]
        os.environ["AWS_SECRET_ACCESS_KEY"] = creds["SecretAccessKey"]
        os.environ["AWS_SESSION_TOKEN"] = creds["SessionToken"]
        os.environ["AWS_DEFAULT_REGION"] = region

        # Open up a new shell
        if os.name == 'nt':
            subprocess.Popen(r"cmd", creationflags=subprocess.CREATE_NEW_CONSOLE)
        else:
            os.system(os.environ['SHELL']) 
Example #3
Source File: controlled_processes.py    From code-jam-5 with MIT License 5 votes vote down vote up
def run(self) -> None:
        self.subprocess = sp.Popen(
            ['pipenv', 'run', 'python', str(bot_script_path)],
            creationflags=sp.CREATE_NEW_CONSOLE,
            cwd=bot_script_path.parent,
        )

        self.subprocess.wait() 
Example #4
Source File: screenshot.py    From colorclass with MIT License 5 votes vote down vote up
def __enter__(self):
        """Entering the `with` block. Runs the process."""
        if not self._kernel32.CreateProcessA(
            None,  # lpApplicationName
            self.command_str,  # lpCommandLine
            None,  # lpProcessAttributes
            None,  # lpThreadAttributes
            False,  # bInheritHandles
            subprocess.CREATE_NEW_CONSOLE,  # dwCreationFlags
            None,  # lpEnvironment
            str(PROJECT_ROOT).encode('ascii'),  # lpCurrentDirectory
            ctypes.byref(self.startup_info),  # lpStartupInfo
            ctypes.byref(self.process_info)  # lpProcessInformation
        ):
            raise ctypes.WinError()

        # Add handles added by the OS.
        self._handles.append(self.process_info.hProcess)
        self._handles.append(self.process_info.hThread)

        # Get hWnd.
        self.hwnd = 0
        for _ in range(int(5 / 0.1)):
            # Takes time for console window to initialize.
            self.hwnd = ctypes.windll.user32.FindWindowA(None, self.startup_info.lpTitle)
            if self.hwnd:
                break
            time.sleep(0.1)
        assert self.hwnd

        # Return generator that yields window size/position.
        return self._iter_pos() 
Example #5
Source File: terminal.py    From thonny with MIT License 5 votes vote down vote up
def _run_in_terminal_in_windows(cmd, cwd, env, keep_open, title=None):
    if keep_open:
        # Yes, the /K argument has weird quoting. Can't explain this, but it works
        quoted_args = " ".join(map(lambda s: s if s == "&" else '"' + s + '"', cmd))
        cmd_line = """start {title} /D "{cwd}" /W cmd /K "{quoted_args}" """.format(
            cwd=cwd, quoted_args=quoted_args, title='"' + title + '"' if title else ""
        )

        subprocess.Popen(cmd_line, cwd=cwd, env=env, shell=True)
    else:
        subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE, cwd=cwd, env=env) 
Example #6
Source File: Machine.py    From Kathara with GNU General Public License v3.0 5 votes vote down vote up
def connect(self, terminal_name):
        logging.debug("Opening terminal for machine %s.", self.name)

        executable_path = utils.get_executable_path(sys.argv[0])

        if not executable_path:
            raise Exception("Unable to find Kathara.")

        connect_command = "%s connect -l %s" % (executable_path, self.name)
        terminal = terminal_name if terminal_name else Setting.get_instance().terminal

        logging.debug("Terminal will open in directory %s." % self.lab.path)

        def unix_connect():
            logging.debug("Opening Linux terminal with command: %s." % connect_command)
            # Command should be passed as an array
            # https://stackoverflow.com/questions/9935151/popen-error-errno-2-no-such-file-or-directory/9935511
            subprocess.Popen([terminal, "-e", connect_command],
                             cwd=self.lab.path,
                             start_new_session=True
                             )

        def windows_connect():
            complete_win_command = "& %s" % connect_command
            logging.debug("Opening Windows terminal with command: %s." % complete_win_command)
            subprocess.Popen(["powershell.exe",
                              '-Command',
                              complete_win_command
                              ],
                             creationflags=subprocess.CREATE_NEW_CONSOLE,
                             cwd=self.lab.path
                             )

        def osx_connect():
            import appscript
            complete_osx_command = "cd \"%s\" && clear && %s && exit" % (self.lab.path, connect_command)
            logging.debug("Opening OSX terminal with command: %s." % complete_osx_command)
            appscript.app('Terminal').do_script(complete_osx_command)

        utils.exec_by_platform(unix_connect, windows_connect, osx_connect) 
Example #7
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def write_windows_console(self, *args):
        retcode = subprocess.call(args,
            # use a new console to not flood the test output
            creationflags=subprocess.CREATE_NEW_CONSOLE,
            # use a shell to hide the console window (SW_HIDE)
            shell=True)
        self.assertEqual(retcode, 0) 
Example #8
Source File: app.py    From Dwarf with GNU General Public License v3.0 5 votes vote down vote up
def _execute_tool(self, qaction):
        if qaction:
            _tools = self.prefs.get('tools')
            if _tools:
                for _tool in _tools:
                    if _tool and _tool['name'] and _tool['name'] != 'sep':
                        if qaction.text() == _tool['name']:
                            try:
                                import subprocess
                                subprocess.Popen(_tool['cmd'], creationflags=subprocess.CREATE_NEW_CONSOLE)
                            except:
                                pass
                            break 
Example #9
Source File: nvkdeamon.py    From NixieVideoKit with MIT License 5 votes vote down vote up
def DeamonHelper(inName, argLen, scriptName, fileHead):
	inName = os.path.join(customDownDir, inName + '.txt')
	lines = SafeReadandWriteHead(inName, fileHead)
	if len(lines):
		inf = codecs.open(inName, 'w+', 'utf-8')
		if fileHead:
			fileHead = [l.strip() + '\n' for l in fileHead]
			inf.writelines(fileHead)
		else:
			inf.write('')
		inf.close()

		while lines:
			args = GrabArgs(lines, argLen)
			lines = lines[len(args):]
			print(inName + ' command: ' + time.ctime())
			for arg in args:
				print(arg)
			# For safety
			time.sleep(0.5)
			subprocess.Popen(
				[
					'py', '-3', os.path.join(scriptDir, scriptName + '.py')
				] + args,
				creationflags = subprocess.CREATE_NEW_CONSOLE
			 ) 
Example #10
Source File: misc.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def execute_in_environment(cmd, prefix=config.root_dir, additional_args=None,
                           inherit=True):
    """Runs ``cmd`` in the specified environment.

    ``inherit`` specifies whether the child inherits stdio handles (for JSON
    output, we don't want to trample this process's stdout).
    """
    binpath, env = environment_for_conda_environment(prefix)

    if sys.platform == 'win32' and cmd == 'python':
        # python is located one directory up on Windows
        cmd = join(binpath, '..', cmd)

    args = shlex.split(cmd)
    if additional_args:
        args.extend(additional_args)

    if inherit:
        stdin, stdout, stderr = None, None, None
    else:
        stdin, stdout, stderr = subprocess.PIPE, subprocess.PIPE, subprocess.PIPE

    if sys.platform == 'win32' and not inherit:
        return subprocess.Popen(args, env=env, close_fds=False,
                                stdin=stdin, stdout=stdout, stderr=stderr,
                                creationflags=subprocess.CREATE_NEW_CONSOLE)
    else:
        return subprocess.Popen(args, env=env, close_fds=False,
                                stdin=stdin, stdout=stdout, stderr=stderr) 
Example #11
Source File: misc.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def launch(fn, prefix=config.root_dir, additional_args=None, background=False):
    info = install.is_linked(prefix, fn[:-8])
    if info is None:
        return None

    if not info.get('type') == 'app':
        raise TypeError('Not an application: %s' % fn)

    binpath, env = environment_for_conda_environment(prefix)
    # allow updating environment variables from metadata
    if 'app_env' in info:
        env.update(info['app_env'])

    # call the entry command
    args = info['app_entry'].split()
    args = [a.replace('${PREFIX}', prefix) for a in args]
    arg0 = find_executable(args[0], env['PATH'])
    if arg0 is None:
        raise Exception('Executable not found: %s' % args[0])
    args[0] = arg0

    cwd = abspath(expanduser('~'))
    if additional_args:
        args.extend(additional_args)
    if sys.platform == 'win32' and background:
        return subprocess.Popen(args, cwd=cwd, env=env, close_fds=False,
                                creationflags=subprocess.CREATE_NEW_CONSOLE)
    else:
        return subprocess.Popen(args, cwd=cwd, env=env, close_fds=False) 
Example #12
Source File: _daemonize_windows.py    From py_daemoniker with The Unlicense 5 votes vote down vote up
def _fork_worker(namespace_path, child_env, pid_file, invocation, chdir,
                 stdin_goto, stdout_goto, stderr_goto, _exit_caller, args):
    ''' Opens a fork worker, shielding the parent from cancellation via
    signal sending. Basically, thanks Windows for being a dick about
    signals.
    '''
    # Find out our PID so the daughter can tell us to exit
    my_pid = os.getpid()
    # Pack up all of the args that the child will need to use.
    # Prepend it to *args
    payload = (my_pid, pid_file, chdir, stdin_goto, stdout_goto,
               stderr_goto, _exit_caller) + args
    
    # Pack it up. We're shielded from pickling errors already because pickle is
    # needed to start the worker.
    # Write the payload to the namespace passer using the highest available
    # protocol
    with open(namespace_path, 'wb') as f:
        pickle.dump(payload, f, protocol=-1)
    
    # Invoke the invocation!
    daemon = subprocess.Popen(
        invocation,
        # This is important, because the parent _forkish is telling the child
        # to run as a daemon via env. Also note that we need to calculate this
        # in the root _daemonize1, or else we'll have a polluted environment
        # due to the '__CREATE_DAEMON__' key.
        env = child_env,
        # This is vital; without it, our process will be reaped at parent
        # exit.
        creationflags = subprocess.CREATE_NEW_CONSOLE,
    )
    # Busy wait until either the daemon exits, or it sends a signal to kill us.
    daemon.wait() 
Example #13
Source File: updater.py    From ExtAnalysis with GNU General Public License v3.0 5 votes vote down vote up
def update():
    '''
    Updates ExtAnalysis
    1. Create the updater child script and save it to temp directory
    2. End self process and start the child script
    '''
    print("\n[i] Creating Updater file")

    child_script = open(helper.fixpath(core.path + '/db/updater.py'), 'r')
    child_script = child_script.read()

    src = child_script.replace('<current_extanalysis_directory>', core.path.replace('\\', '\\\\'))
    src = src.replace('<github_zip_url>', core.github_zip)

    print('[i] Moving updater file to temp directory')
    temp_dir = tempfile.gettempdir()

    updater_script = helper.fixpath(temp_dir + '/update_extanalysis.py')
    f = open(updater_script, 'w+')
    f.write(src)
    f.close()

    python_loc = sys.executable

    print('[i] Starting Updater script')

    if sys.platform == 'win32':
        os.chdir(temp_dir)
        command = [python_loc, 'update_extanalysis.py']
        subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE, shell=False)
        print('[i] Killing self... Next time we meet I will be a better version of myself ;)')
        exit()
    else:
        os.chdir(temp_dir)
        command = ['x-terminal-emulator', '-e', python_loc, updater_script]
        subprocess.Popen(command, shell=False)
        print('[i] Killing self... Next time we meet I will be a better version of myself ;)')
        exit() 
Example #14
Source File: vivado_task.py    From pyvivado with MIT License 5 votes vote down vote up
def run(self):
        '''
        Spawn the process that will run the vivado process.
        '''
        cwd = os.getcwd()
        os.chdir(self.directory)
        stdout_fn = 'stdout.txt' 
        stderr_fn = 'stderr.txt' 
        command_fn = 'command.tcl' 
        if os.name == 'nt':
            commands = [config.vivado, '-log', stdout_fn, '-mode', 'batch',
                        '-source', command_fn]
            logger.debug('running vivado task in directory {}'.format(self.directory))
            logger.debug('command is {}'.format(' '.join(commands)))
            self.process = subprocess.Popen(
                commands,
                # So that process stays alive when terminal is closed
                # in Windows.
                # Commented out because doesn't seem to be working now.
                creationflags=subprocess.CREATE_NEW_CONSOLE,
            )
            logger.debug('started process')
        else:
            commands = [config.vivado, '-mode', 'batch', '-source',
                        command_fn]
            self.launch_unix_subprocess(
                commands, stdout_fn=stdout_fn, stderr_fn=stderr_fn)
        os.chdir(cwd) 
Example #15
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 #16
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def write_windows_console(self, *args):
        retcode = subprocess.call(args,
            # use a new console to not flood the test output
            creationflags=subprocess.CREATE_NEW_CONSOLE,
            # use a shell to hide the console window (SW_HIDE)
            shell=True)
        self.assertEqual(retcode, 0) 
Example #17
Source File: bls.py    From python_banyan with GNU Affero General Public License v3.0 5 votes vote down vote up
def spawn_local(self, idx):
        """
        This method launches processes that are needed to run on this computer
        :param idx: An index into launch_db
        """

        # get the launch entry in launch_db
        db_entry = self.launch_db[idx]

        # skip over the entry for the backplane
        # launch the process either in its own window or just launch it.
        # differentiate between windows and other os's.
        if not db_entry['command_string'] == 'backplane':
            if sys.platform.startswith('win32'):
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(db_entry['command_string'],
                                      creationflags=subprocess.CREATE_NEW_CONSOLE)
                else:
                    command_list = db_entry['command_string']
                    self.proc = Popen(command_list, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
            else:
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(['xterm', '-e', db_entry['command_string']],
                                      stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                                      stdout=subprocess.PIPE)
                else:
                    command_list = db_entry['command_string'].split(' ')
                    self.proc = Popen(command_list)

            # update the entry with the launch information
            db_entry['process'] = self.proc
            db_entry['process_id'] = self.proc.pid
            print('{:35} PID = {}'.format(db_entry['command_string'], str(self.proc.pid)))

            # allow a little time for the process to startup
            try:
                time.sleep(0.5)
            except (KeyboardInterrupt, SystemExit):
                self.clean_up() 
Example #18
Source File: screenshot.py    From terminaltables with MIT License 5 votes vote down vote up
def __enter__(self):
        """Entering the `with` block. Runs the process."""
        if not self._kernel32.CreateProcessA(
            None,  # lpApplicationName
            self.command_str,  # lpCommandLine
            None,  # lpProcessAttributes
            None,  # lpThreadAttributes
            False,  # bInheritHandles
            subprocess.CREATE_NEW_CONSOLE,  # dwCreationFlags
            None,  # lpEnvironment
            str(PROJECT_ROOT).encode('ascii'),  # lpCurrentDirectory
            ctypes.byref(self.startup_info),  # lpStartupInfo
            ctypes.byref(self.process_info)  # lpProcessInformation
        ):
            raise ctypes.WinError()

        # Add handles added by the OS.
        self._handles.append(self.process_info.hProcess)
        self._handles.append(self.process_info.hThread)

        # Get hWnd.
        self.hwnd = 0
        for _ in range(int(5 / 0.1)):
            # Takes time for console window to initialize.
            self.hwnd = ctypes.windll.user32.FindWindowA(None, self.startup_info.lpTitle)
            if self.hwnd:
                break
            time.sleep(0.1)
        assert self.hwnd

        # Return generator that yields window size/position.
        return self._iter_pos() 
Example #19
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def write_windows_console(self, *args):
        retcode = subprocess.call(args,
            # use a new console to not flood the test output
            creationflags=subprocess.CREATE_NEW_CONSOLE,
            # use a shell to hide the console window (SW_HIDE)
            shell=True)
        self.assertEqual(retcode, 0) 
Example #20
Source File: external.py    From cross3d with MIT License 5 votes vote down vote up
def runScript(cls, script, version=None, architecture=64, language=ScriptLanguage.Python, debug=False, headless=True):

		# If the script argument is a path to a file.
		if os.path.exists(script):
			with open(script, 'r') as fle:
				script = fle.read()

		scriptPath = os.path.splitext(cls.scriptPath())[0] + '.py'
		with open(scriptPath, 'w') as fle:
			fle.write(script)
	
		binary = os.path.join(cls.binariesPath(version, architecture), 'mayabatch.exe' if headless else 'maya.exe')
		args = [binary, '-console', '-verbosePython', scriptPath]
		subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_CONSOLE, env=os.environ)

		# TODO: Need to figure out a way to return False if the script has failed.
		return True 
Example #21
Source File: external.py    From cross3d with MIT License 5 votes vote down vote up
def runScript(cls, script, version=None, architecture=64, language=ScriptLanguage.Python, debug=False, headless=True):

		if os.path.exists(script):
			scriptPath = script

		else:
			scriptPath = cls.scriptPath()
			with open(scriptPath, "w") as fle:
				fle.write(script)

		if language == ScriptLanguage.Python:
			scriptTemplate = os.path.join(os.path.dirname(__file__), 'templates', 'external_python_script.mstempl')

			with open(scriptTemplate) as fle:
				script = fle.read().format(scriptPath =scriptPath, debug=debug)
			
			scriptPath = os.path.splitext(cls.scriptPath())[0] + '.ms'

			with open(scriptPath, "w") as fle:
				fle.write(script)

		binary = os.path.join(cls.binariesPath(version, architecture), '3dsmax.exe')
		process = subprocess.Popen([binary, '-U', 'MAXScript', scriptPath], creationflags=subprocess.CREATE_NEW_CONSOLE, env=os.environ)

		# TODO: Need to figure out a way to return False if the script has failed.
		return True 
Example #22
Source File: utility.py    From gxpy with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def run_external_python(script, script_args='',
                        python_args='',
                        shared_dict=None,
                        console=True,
                        catcherr=True):
    """
    Run a python script as an external program, returning results as a dictionary.
    External program calls gxpy.utility.get_shared_dict() to get the caller's dictionary,
    and gxpy.utility.set_shared_dict(return_dictionary) to return a dictionary back to caller.

    :param script:      full path of the python script
    :param shared_dict: dictionary passed to the external script (get_shared_dict() to retrieve)
    :param script_args: command line arguments as a string
    :param python_args: command line arguments as a string
    :param console:     True (default) will create a separate console for the process.
    :param catcherr:    True (default) Catch and re-raise errors from the sub-process.
    :returns:           dictionary passed back from caller via set_shared_dict(dict)

    .. versionadded:: 9.1
    """

    if not os.path.isfile(script):
        raise UtilityException(_t('Cannot find script: {}'.format(script)))

    py = sys.executable
    if not py.lower().endswith('python.exe'):
        s = gxapi.str_ref()
        gxapi.GXSYS.get_env('PYTHON_HOME', s)
        py = os.path.join(s.value, 'python.exe')

    command = "\"{}\" {} \"{}\" {}".format(py, python_args, script, script_args)

    set_shared_dict(shared_dict)

    kwargs = {}
    if console:
        kwargs['creationflags'] = subprocess.CREATE_NEW_CONSOLE

    if hasattr(subprocess, 'run'):
        if catcherr:
            kwargs['stderr'] = subprocess.PIPE
        cp = subprocess.run(command, **kwargs)
        if catcherr and cp.returncode != 0:
            raise UtilityException(_t('\n\nExternal python error:\n\n{}').format(cp.stderr.decode("utf-8")))

    else:  # use call, python 3.4...
        err = subprocess.call(command, **kwargs)
        if catcherr and err != 0:
            raise UtilityException(_t('\n\nExternal python error({}) running: {}').format(err, command))

    return get_shared_dict() 
Example #23
Source File: launch_minecraft_in_background.py    From marLo with MIT License 4 votes vote down vote up
def launch_minecraft_in_background(minecraft_path, ports=None, timeout=360, replaceable=False):
    """
    Module deprecated in favor of :meth:`marlo.utils.launch_clients`
    """
    if ports is None:
        ports = []
    if len(ports) == 0:
        ports = [10000]  # Default
    processes = []
    for port in ports:
        if _port_has_listener(port):
            print('Something is listening on port', port, '- will assume Minecraft is running.')
            continue
        replaceable_arg = "" if not replaceable else " -replaceable "
        print('Nothing is listening on port', port, '- will attempt to launch Minecraft from a new terminal.')
        if os.name == 'nt':
            p = subprocess.Popen([minecraft_path + '/launchClient.bat', '-port', str(port), replaceable_arg.strip()],
                             creationflags=subprocess.CREATE_NEW_CONSOLE, close_fds=True)
        elif sys.platform == 'darwin':
            # Can't pass parameters to launchClient via Terminal.app, so create a small launch
            # script instead.
            # (Launching a process to run the terminal app to run a small launch script to run
            # the launchClient script to run Minecraft... is it possible that this is not the most
            # straightforward way to go about things?)
            launcher_file = "/tmp/launcher_" + str(os.getpid()) + ".sh"
            tmp_file = open(launcher_file, "w")
            tmp_file.write(minecraft_path + '/launchClient.sh -port ' + str(port) + replaceable_arg)
            tmp_file.close()
            os.chmod(launcher_file, 0o700)
            p = subprocess.Popen(['open', '-a', 'Terminal.app', launcher_file])
        else:
            p = subprocess.Popen(minecraft_path + "/launchClient.sh -port " + str(port) + replaceable_arg,
                             close_fds=True, shell=True,
                             stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        processes.append(p)
        print('Giving Minecraft some time to launch... ')
        launched = False
        for i in range(timeout // 3):
            print('.', end=' ')
            time.sleep(3)
            if _port_has_listener(port):
                print('ok')
                launched = True
                break
        if not launched:
            print('Minecraft not yet launched. Giving up.')
            exit(1)
    return processes 
Example #24
Source File: PyYapf.py    From PyYapf with Apache License 2.0 4 votes vote down vote up
def __enter__(self):
        """Sublime calls plugins 'with' a context manager."""
        # determine encoding
        self.encoding = self.view.encoding()
        if self.encoding in ['Undefined', None]:
            self.encoding = self.get_setting('default_encoding')
            self.debug(
                'Encoding is not specified, falling back to default %r',
                self.encoding
            )
        else:
            self.debug('Encoding is %r', self.encoding)

        # custom style options?
        custom_style = self.get_setting("config")
        if custom_style:
            # write style file to temporary file
            self.custom_style_fname = save_style_to_tempfile(custom_style)
            self.debug(
                'Using custom style (%s):\n%s', self.custom_style_fname,
                open(self.custom_style_fname).read().strip()
            )
        else:
            self.custom_style_fname = None

        # use shlex.split because we should honor embedded quoted arguemnts
        self.popen_args = shlex.split(self.find_yapf(), posix=False)
        if self.custom_style_fname:
            self.popen_args += ['--style', self.custom_style_fname]

        # use directory of current file so that custom styles are found
        # properly
        fname = self.view.file_name()
        self.popen_cwd = os.path.dirname(fname) if fname else None

        # specify encoding in environment
        self.popen_env = os.environ.copy()
        self.popen_env['LANG'] = str(self.encoding)

        # win32: hide console window
        if sys.platform in ('win32', 'cygwin'):
            self.popen_startupinfo = subprocess.STARTUPINFO()
            self.popen_startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            self.popen_startupinfo.wShowWindow = subprocess.SW_HIDE
        else:
            self.popen_startupinfo = None

        # clear marked regions and status
        self.view.erase_regions(KEY)
        self.view.erase_status(KEY)
        self.errors = []
        return self 
Example #25
Source File: blc.py    From python_banyan with GNU Affero General Public License v3.0 4 votes vote down vote up
def spawn_local(self, idx):
        """
        This method launches processes that are needed to run on this computer.
        :param idx: An index into launch_db
        """

        # get the launch entry in launch_db
        db_entry = self.launch_db[idx]

        # skip over the entry for the backplane.
        # there shouldn't be one for the client, but the code is
        # kept consist with the server.
        # launch the process either in its own window or just launch it.
        # differentiate between windows and other os's.
        if not db_entry['command_string'] == 'backplane':
            if sys.platform.startswith('win32'):
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(db_entry['command_string'],
                                      creationflags=subprocess.CREATE_NEW_CONSOLE)
                else:
                    command_list = db_entry['command_string']
                    self.proc = Popen(command_list, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
            else:
                if db_entry['spawn'] == 'yes':
                    self.proc = Popen(['xterm', '-e', db_entry['command_string']],
                                      stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                                      stdout=subprocess.PIPE)
                else:
                    command_list = db_entry['command_string'].split(' ')
                    self.proc = Popen(command_list)

            # update the entry with the launch information
            db_entry['process'] = self.proc
            db_entry['process_id'] = self.proc.pid
            print('{:35} PID = {}'.format(db_entry['command_string'], str(self.proc.pid)))

            # allow a little time for the process to startup
            try:
                time.sleep(0.5)
            except (KeyboardInterrupt, SystemExit):
                # self.scheduler.shutdown()
                self.clean_up()
                sys.exit(0) 
Example #26
Source File: test_codes.py    From colorclass with MIT License 4 votes vote down vote up
def test_disable_colors_piped(tty):
    """Verify colors enabled by default when piped to TTY and disabled when not.

    :param bool tty: Pipe to TTY/terminal?
    """
    assert_statement = 'assert __import__("colorclass").codes.ANSICodeMapping.disable_if_no_tty() is {bool}'
    command_colors_enabled = [sys.executable, '-c', assert_statement.format(bool='False')]
    command_colors_disabled = [sys.executable, '-c', assert_statement.format(bool='True')]

    # Run piped to this pytest process.
    if not tty:  # Outputs piped to non-terminal/non-tty. Colors disabled by default.
        proc = subprocess.Popen(command_colors_disabled, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        output = proc.communicate()
        assert not output[0]
        assert not output[1]
        assert proc.poll() == 0
        return

    # Run through a new console window (Windows).
    if IS_WINDOWS:
        c_flags = subprocess.CREATE_NEW_CONSOLE
        proc = subprocess.Popen(command_colors_enabled, close_fds=True, creationflags=c_flags)
        proc.communicate()  # Pipes directed towards new console window. Not worth doing screenshot image processing.
        assert proc.poll() == 0
        return

    # Run through pseudo tty (Linux/OSX).
    master, slave = __import__('pty').openpty()
    proc = subprocess.Popen(command_colors_enabled, stderr=subprocess.STDOUT, stdout=slave, close_fds=True)
    os.close(slave)

    # Read output.
    output = ''
    while True:
        try:
            data = os.read(master, 1024).decode()
        except OSError as exc:
            if exc.errno != errno.EIO:  # EIO means EOF on some systems.
                raise
            data = None
        if data:
            output += data
        elif proc.poll() is None:
            time.sleep(0.01)
        else:
            break
    os.close(master)
    assert not output
    assert proc.poll() == 0 
Example #27
Source File: external.py    From cross3d with MIT License 4 votes vote down vote up
def runScript(cls, script, version=None, architecture=64, language=ScriptLanguage.Python, debug=False, headless=True):

		# If the script argument is a path to a file.
		if os.path.exists(script):

			# If the language is MEL we just use the script as is.
			if language == ScriptLanguage.MEL:
				scriptPath = script

			# If the language is Python we parse the file to get the content.
			elif language == ScriptLanguage.Python:
				with open(script, 'r') as fle:
					script = fle.read()

		if language == ScriptLanguage.Python:
			scriptTemplate = os.path.join(os.path.dirname(__file__), 'templates', 'external_python_script.meltempl')
			pythonScritpPath = os.path.splitext(cls.scriptPath())[0] + '.py'

			with open(pythonScritpPath, 'w') as fle:
				fle.write(script)

			with open(scriptTemplate) as fle:
				script = fle.read().format(debug=unicode(debug).lower())
				
			scriptPath = os.path.splitext(cls.scriptPath())[0] + '.mel'
			logPath = os.path.splitext(cls.scriptPath())[0] + '.log'
			with open(scriptPath, "w") as fle:
				fle.write(script)

		#--------------------------------------------------------------------------------
		# Developer's note: When running headless, these three messages are to be expected
		# I did my testing in Maya 2015 with Bonus Tools installed. The first two lines are because
		# bifrost doesn't properly check if it is in mayabatch mode. The third is because a script
		# in Bonus Tools also does not check if its in mayabatch mode.
		#--------------------------------------------------------------------------------
		# 1 error generated.
		# Error while processing C:\Program Files\Autodesk\Maya2015\plug-ins\bifrost\db\presets\__rootincludeall__.h.
		# Error: file: C:/ProgramData/Autodesk/ApplicationPlugins/MayaBonusTools/Contents/scripts-2015/bonusToolsMenu.mel line 1546: UI commands can't be run in batch mode.
		#--------------------------------------------------------------------------------

		binary = os.path.join(cls.binariesPath(version, architecture), 'mayabatch.exe' if headless else 'maya.exe')
		args = [binary, '-script', scriptPath, '-log', logPath]
		if debug and headless:
			# run mayabatch inside a cmd.exe prompt so you can see the output of mayabatch
			args = ['cmd.exe', '/k'] + args
		process = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_CONSOLE, env=os.environ)

		# TODO: Need to figure out a way to return False if the script has failed.
		return True