Python subprocess.CREATE_NEW_CONSOLE() Examples

The following are code examples for showing how to use subprocess.CREATE_NEW_CONSOLE(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: shimit   Author: cyberark   File: aws.py    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 2
Project: AutoPK   Author: guitanj   File: goEngin-SamePoPK(Stop update).py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, command, cwdstr):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.CREATE_NEW_CONSOLE \
                     | subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = Popen(command, bufsize=1,stdin=PIPE, stdout=PIPE, \
                        stderr=PIPE,startupinfo=si,cwd=cwdstr)
        print('leelaz threading is started...',self.process.pid,'poll:',self.process.poll())

        #gtp辅助的运算信息,比如genmove中的过程,胜率,其他选点等都在stderr中输出
        self.stderr_queue = Queue()
        Thread(target=self.consume_stderr).start()
        #print('get stderr threading is started...',self.process.poll())
        
        #程序调用一开始就出错的话,比如命令行用错了,报错信息在stdout中输出
        #运行起来,正常的gtp输出信息在stdout中
        self.stdout_queue = Queue()
        Thread(target=self.consume_stdout).start()
        #print('get stdout threading is started...',self.process.poll())

    #读取stderr信息流,写入stderrQ 
Example 3
Project: AutoPK   Author: guitanj   File: autoPK-SameTime.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, command, cwdstr):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.CREATE_NEW_CONSOLE \
                     | subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = Popen(command, bufsize=1,stdin=PIPE, stdout=PIPE, \
                        stderr=PIPE,startupinfo=si,cwd=cwdstr)
        print('leelaz threading is started...',self.process.pid,'poll:',self.process.poll())

        #gtp辅助的运算信息,比如genmove中的过程,胜率,其他选点等都在stderr中输出
        self.stderr_queue = Queue()
        Thread(target=self.consume_stderr).start()
        #print('get stderr threading is started...',self.process.poll())
        
        #程序调用一开始就出错的话,比如命令行用错了,报错信息在stdout中输出
        #运行起来,正常的gtp输出信息在stdout中
        self.stdout_queue = Queue()
        Thread(target=self.consume_stdout).start()
        #print('get stdout threading is started...',self.process.poll())

    #读取stderr信息流,写入stderrQ 
Example 4
Project: AutoPK   Author: guitanj   File: autoPK.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, command, cwdstr):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.CREATE_NEW_CONSOLE \
                     | subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = Popen(command, bufsize=1,stdin=PIPE, stdout=PIPE, \
                        stderr=PIPE,startupinfo=si,cwd=cwdstr)
        print('leelaz threading is started...',self.process.pid,'poll:',self.process.poll())

        #gtp辅助的运算信息,比如genmove中的过程,胜率,其他选点等都在stderr中输出
        self.stderr_queue = Queue()
        Thread(target=self.consume_stderr).start()
        #print('get stderr threading is started...',self.process.poll())
        
        #程序调用一开始就出错的话,比如命令行用错了,报错信息在stdout中输出
        #运行起来,正常的gtp输出信息在stdout中
        self.stdout_queue = Queue()
        Thread(target=self.consume_stdout).start()
        #print('get stdout threading is started...',self.process.poll())

    #读取stderr信息流,写入stderrQ 
Example 5
Project: AutoPK   Author: guitanj   File: goEngin-SameTimePK(Stop update).py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, command, cwdstr):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.CREATE_NEW_CONSOLE \
                     | subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = Popen(command, bufsize=1,stdin=PIPE, stdout=PIPE, \
                        stderr=PIPE,startupinfo=si,cwd=cwdstr)
        print('leelaz threading is started...',self.process.pid,'poll:',self.process.poll())

        #gtp辅助的运算信息,比如genmove中的过程,胜率,其他选点等都在stderr中输出
        self.stderr_queue = Queue()
        Thread(target=self.consume_stderr).start()
        #print('get stderr threading is started...',self.process.poll())
        
        #程序调用一开始就出错的话,比如命令行用错了,报错信息在stdout中输出
        #运行起来,正常的gtp输出信息在stdout中
        self.stdout_queue = Queue()
        Thread(target=self.consume_stdout).start()
        #print('get stdout threading is started...',self.process.poll())

    #读取stderr信息流,写入stderrQ 
Example 6
Project: Raid-Toolbox   Author: DeadBread76   File: RTB.py    GNU General Public License v2.0 6 votes vote down vote up
def serversmasher():
    global currentattacks
    clear()
    if command_line_mode == 1:
        print ("The config file for the ServerSmasher is in RTBFiles/smconfig.py, please add token before starting.")
    if sys.platform.startswith('win32'):
        if server_smasher_in_main_window == 1:
            p = subprocess.Popen([sys.executable,'RTBFiles/ServerSmasher/serversmasher.py',"?",menu1,menu2,str(no_tk_mode)])
            p.wait()
        else:
            subprocess.Popen([sys.executable,'RTBFiles/ServerSmasher/serversmasher.py',"?",menu1,menu2,str(no_tk_mode)],creationflags=CREATE_NEW_CONSOLE)
    else:
        if server_smasher_in_main_window == 1:
            p = subprocess.Popen([sys.executable,'RTBFiles/ServerSmasher/serversmasher.py',"?",menu1,menu2,str(no_tk_mode)])
            p.wait()
        else:
            subprocess.call(['gnome-terminal', '-x', sys.executable,'RTBFiles/ServerSmasher/serversmasher.py',"?",menu1,menu2,str(no_tk_mode)])
    if server_smasher_in_main_window == 1:
        pass
    elif no_tk_mode == 1:
        pass
    elif command_line_mode == 1:
        time.sleep(5)
    main() 
Example 7
Project: pyDAPLink   Author: geky   File: popen.py    Apache License 2.0 6 votes vote down vote up
def popen_and_detach(args):
    os_flags = {}

    # Disowning processes in linux/mac
    if hasattr(os, 'setsid'):
        os_flags['preexec_fn'] = os.setsid

    # Disowning processes in windows
    if hasattr(subprocess, 'STARTUPINFO'):
        # Detach the process
        os_flags['creationflags'] = subprocess.CREATE_NEW_CONSOLE

        # Hide the process console
        startupinfo = subprocess.STARTUPINFO()
	startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        os_flags['startupinfo'] = startupinfo

    # Redirect child's io
    with open(os.devnull, 'w+') as null:
        return Popen(args, stdin=null, stdout=null, stderr=null, **os_flags) 
Example 8
Project: NEP   Author: enriquecoronadozu   File: helpers.py    MIT License 6 votes vote down vote up
def setNEPpath(new_path):
    """ Set path to NEP Workspace

    Parameters
    ----------

    new_path: string
        New path for NEP workspace

    """
    import os

    if os.environ.get('OS','') == 'Windows_NT':
        from subprocess import CREATE_NEW_CONSOLE
        command = 'setx NEP_WS "' + new_path + '"'
        Popen(command, creationflags=CREATE_NEW_CONSOLE)
        
    os.environ["NEP_WS"] = new_path 
Example 9
Project: pywikibot   Author: metakgp   File: ui_tests.py    MIT License 6 votes vote down vote up
def setUpProcess(cls, command):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.STARTF_USESTDHANDLES
        cls._process = subprocess.Popen(command,
                                        creationflags=subprocess.CREATE_NEW_CONSOLE)

        cls._app.connect_(process=cls._process.pid)

        # set truetype font (Lucida Console, hopefully)
        try:
            window = cls._app.window_()
        except Exception as e:
            cls.tearDownProcess()
            raise unittest.SkipTest('Windows package pywinauto could not locate window: %r'
                                    % e)

        try:
            window.TypeKeys('% {UP}{ENTER}^L{HOME}L{ENTER}', with_spaces=True)
        except Exception as e:
            cls.tearDownProcess()
            raise unittest.SkipTest('Windows package pywinauto could not use window TypeKeys: %r'
                                    % e) 
Example 10
Project: flight-lab   Author: google   File: windows.py    Apache License 2.0 5 votes vote down vote up
def _launch_app(self):
    args = [self._bin_path] + self._arguments
    self.logger.debug('[App - {0}] Executing "{1}"...'.format(
        self._name, ' '.join(args)))

    self.emit('starting', self)

    proc = None
    info = subprocess.STARTUPINFO()
    if self._start_minimized:
      info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
      info.wShowWindow = _SW_MINIMIZE

    try:
      proc = subprocess.Popen(
          args,
          cwd=self._working_dir,
          creationflags=subprocess.CREATE_NEW_CONSOLE,
          close_fds=True,
          startupinfo=info)
    except Exception as e:
      self.logger.debug('[App - {0}] Failed to launch. {1}'.format(
          self._name, e))
      return None

    self.emit('started', self)
    return proc 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    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 12
Project: qpboost   Author: LotusEngineering   File: qutest.py    MIT License 5 votes vote down vote up
def run_program(argumentList, startInConsole):
        """ Helper method for starting programs like qspy and target 
        
        Args:
          argumentList : Popen list where first item is program name
          startInConsole : bool, if True starts in new console
        
        Returns:
          A process ID that can be used to terminate the program
        """

        if sys.platform == 'win32':
            if startInConsole:
                process_id = Popen(argumentList, creationflags=CREATE_NEW_CONSOLE)
            else:
                process_id = Popen(argumentList)
        elif sys.platform == 'linux':
            if startInConsole:
                cmd_list = ['gnome-terminal', '--disable-factory', '-e']
                argstring = " ".join(argumentList)
                cmd_list.append(argstring)
                process_id = Popen(cmd_list, preexec_fn=os.setpgrp)
            else:
                process_id = Popen(argumentList, preexec_fn=os.setpgrp)

        elif sys.platform == 'darwin':
            # Don't know if this works, doubt it
            if startInConsole:
                cmd_list = ['open', '-W', '-a', 'Terminal.app', argumentList[0], '--args']
                argstring = " ".join(argumentList[1:])
                cmd_list.append(argstring)
                process_id = Popen(cmd_list)
            else:
                process_id = Popen(argumentList)

        else:
            assert False, "Unknown OS platform:{0}".format(sys.platform)
            
        return process_id 
Example 13
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.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 14
Project: VapourSynth-Super-Resolution-Helper   Author: AlphaAtlas   File: Alpha_SharedFunctions.py    MIT License 5 votes vote down vote up
def compact(directory):
    subprocess.Popen(["compact", "/C", "/S", "/I", "/Q", directory], creationflags=subprocess.CREATE_NEW_CONSOLE) 
Example 15
Project: python_banyan   Author: MrYsLab   File: bls.py    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 16
Project: eduActiv8   Author: imiolek-ireneusz   File: speaker.py    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 17
Project: pyvivado   Author: benreynwar   File: vivado_task.py    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 18
Project: NukeBatchRender   Author: NateScarlet   File: menu.py    GNU General Public License v3.0 5 votes vote down vote up
def _add_menu():
    sys.path[0] = join(__folder__, 'lib')
    from batchrender.config import CONFIG

    launch_script_path = join(__folder__, 'launch.py')

    def batchrender():
        """For nuke menu call.  """

        CONFIG.read()
        CONFIG['NUKE'] = sys.executable

        if sys.platform == 'win32':
            # Try use built executable
            try:
                dist_dir = join(__folder__, 'dist')
                exe_path = sorted([join(dist_dir, i)
                                   for i in listdir(dist_dir)
                                   if i.endswith('.exe') and i.startswith('batchrender')],
                                  key=getmtime, reverse=True)[0]
                webbrowser.open(exe_path)
                return
            except (IndexError, OSError):
                LOGGER.debug('Executable not found in %s', dist_dir)

        args = [sys.executable, '--tg', launch_script_path]
        if sys.platform == 'win32':
            args = [join(dirname(sys.executable), 'python.exe'),
                    launch_script_path]
            kwargs = {'creationflags': subprocess.CREATE_NEW_CONSOLE}
        else:
            args = '"{0[0]}" {0[1]} "{0[2]}"'.format(args)
            kwargs = {'shell': True, 'executable': 'bash'}
        subprocess.Popen(args, **kwargs)

    globals()['batchrender'] = batchrender

    menubar = nuke.menu("Nuke")
    m = menubar.addMenu('工具')
    m.addCommand('批渲染', batchrender) 
Example 19
Project: google-plusone-bot   Author: SkullTech   File: wdstart.py    MIT License 5 votes vote down vote up
def start_selenium_server():
    seleniumserver_path = find_file(name='selenium-server-standalone-2.50.1.jar', path=os.getcwd())
    cmd = ['java', '-jar', seleniumserver_path]
    server = subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE)


##    Starts the Selenium Webdriver.
##    Uses broswer driver_name. Custom user-agent and profile can be passed as user_agent and profile_path, respectively. 
Example 20
Project: ExtAnalysis   Author: Tuhinshubhra   File: updater.py    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 21
Project: Splunking-Crime   Author: nccgroup   File: misc.py    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 22
Project: Splunking-Crime   Author: nccgroup   File: misc.py    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 23
Project: Dwarf   Author: iGio90   File: app.py    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 24
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_os.py    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 25
Project: cells   Author: AlesTsurko   File: test_os.py    MIT License 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 26
Project: Kathara   Author: KatharaFramework   File: Machine.py    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 27
Project: python_banyan   Author: MrYsLab   File: blc.py    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 28
Project: NEP   Author: enriquecoronadozu   File: helpers.py    MIT License 4 votes vote down vote up
def nepmaster(version="2", param =""):
    """
        Launch master in NEP_WS

        Parameters
        ----------
        version : string
            Python version, 0 for default, 2 for Python 2 and 3 for Python 3

        param : string
            Can be "local", or "network"
    """

    if os.environ.get('OS','') == 'Windows_NT':
        from subprocess import CREATE_NEW_CONSOLE

    nep_ws = nep.getNEPpath()
    script = "master"
    command = "python " + nep_ws + "/" + script + ".py"+ " " + param

    if os.environ.get('OS','') == 'Windows_NT':

        if version == "2": #If more that one python version, specify Python 2
            print ("Running in Python 2")
            command = "py -2 " + nep_ws + "/" + module + "/" + script + ".py"+ " " + parameters
        elif version == "3": #If more that one python version, specify Python 3
            print ("Running in Python 3")
            command = "py -3 " + nep_ws + "/" + module + "/" + script + ".py"+ " " + parameters

        print ("Windows launcher in new console .......")
        Popen(command, creationflags=CREATE_NEW_CONSOLE)
    else: 
        print ("OSX launcher .......")

        if version == "2": #If more that one python version, specify Python 2
            print ("Running in Python 2")
            command = "python2 " + nep_ws + "/" + module + "/" + script + ".py"+ " " + parameters
        elif version == "3": #If more that one python version, specify Python 3
            print ("Running in Python 3")
            command = "python3 " + nep_ws + "/" + module + "/" + script + ".py"+ " " + parameters

        import applescript

        tell = 'tell application "Terminal" to do script '
        complete = tell + '"' +  command + '"'

        applescript.AppleScript(complete).run() 
Example 29
Project: gxpy   Author: GeosoftInc   File: utility.py    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 30
Project: mini-tools   Author: 3xploit-db   File: rat.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def main():
    global host, port, output

    while True:
        cmd = raw_input("[*] [email protected]:~# ").lower()

        if cmd == "help":
            help()

        elif cmd == 'banner':
            os.system("clear")
            logo()
            main()

        elif "clear" in cmd:
            os.system("clear")

        elif "set host" in cmd:
            host = cmd.split()[-1]

        elif "set port" in cmd:
            port = int(cmd.split()[-1])

        elif "set output" in cmd:
            output = cmd.split()[-1]

        elif cmd == "show values":
            print "\n[+] HOST   : %s\n[+] PORT   : %s\n[+] OUTPUT : %s\n"%(host, port,output)

        elif cmd == "generate payload" or cmd == "generate":
            if host != " " and port != " " and output != " ":
                print("[+] Generating Payload . . .")
                sleep(1)
                print("[*] Using Configuration . . .\n |_ HOST   : "+host+"\n |_ PORT   : "+str(port)+"\n |_ OUTPUT : "+output)
                sleep(3)
                os.system("sh modules/gen.sh "+host+" "+str(port)+" "+output)
                print("[+] Generating Success . . .")
                sleep(1)
                main()
            else:
                print "\n[!] HOST   : %s\n[!] PORT   : %s\n[!] OUTPUT : %s\n"%(host,port,output)

        elif cmd == "start" or cmd == "run" or cmd == "start listener":
            if host != " " and port != " ":
                if os.name == "nt":
                    subprocess.Popen([sys.executable, 'modules/listener.py', host, str(port)], creationflags=subprocess.CREATE_NEW_CONSOLE)
                else:
                    os.system(sys.executable + " modules/listener.py %s %s"%(host, str(port)))
            else:
                print "\n[!] Host : %s\n[!] Port : %s\n"%(host,port)
        else:
            print("[!] Check Your Command . . .")
            main() 
Example 31
Project: ftrack-hooks   Author: tokejepsen   File: quicktime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def launch_subprocess(self, event):

        applicationIdentifier = event["data"]["applicationIdentifier"]
        application = self.applicationStore.getApplication(
            applicationIdentifier
        )
        context = event["data"].copy()
        context["source"] = event["source"]
        command = self.launcher._getApplicationLaunchCommand(
            application, context
        )

        success = True
        message = '{0} application started.'.format(application['label'])

        component_file = event["data"]["values"]["component"]['filename']

        command.append(component_file)

        try:
            options = dict(
                close_fds=True
            )

            # Ensure subprocess is detached so closing connect will not
            # also close launched applications.
            if sys.platform == 'win32':
                options['creationflags'] = subprocess.CREATE_NEW_CONSOLE
            else:
                options['preexec_fn'] = os.setsid

            self.logger.debug(
                'Launching {0} with options {1}'.format(command, options)
            )
            process = subprocess.Popen(command, **options)

        except (OSError, TypeError):
            self.logger.exception(
                '{0} application could not be started with command "{1}".'
                    .format(applicationIdentifier, command)
            )

            success = False
            message = '{0} application could not be started.'.format(
                application['label']
            )

        else:
            self.logger.debug(
                '{0} application started. (pid={1})'.format(
                    applicationIdentifier, process.pid
                )
            )

        return {
            'success': success,
            'message': message
        } 
Example 32
Project: artisan   Author: artisan-roaster-scope   File: main.py    GNU General Public License v3.0 4 votes vote down vote up
def callprogram(self):
        try:
#            output = os.popen(aw.ser.externalprogram,"r").readline()
            # we try to set the users standard environment, replacing the one pointing to the restrictive python build in Artisan
            my_env = aw.calc_env()
        
            # hide the console window on Windows 
            startupinfo = None  
            if platf == 'Windows':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = subprocess.SW_HIDE
            
            if platf == 'Windows':
                cmd_str = os.path.expanduser(aw.ser.externalprogram)
                p = subprocess.Popen(cmd_str,env=my_env,stdout=subprocess.PIPE,startupinfo=startupinfo,shell=True)
            else:
                p = subprocess.Popen([os.path.expanduser(c) for c in shlex.split(aw.ser.externalprogram)],env=my_env,stdout=subprocess.PIPE,startupinfo=startupinfo)
            output = p.communicate()[0].decode('UTF-8')
            
            tx = aw.qmc.timeclock.elapsed()/1000.
            if "," in output:
                parts = output.split(",")
                if len(parts) > 2:
                    aw.qmc.program_t3 = float(parts[2].strip())
                    if len(parts) > 3:
                        aw.qmc.program_t4 = float(parts[3].strip())
                        if len(parts) > 4:
                            aw.qmc.program_t5 = float(parts[4].strip())
                            if len(parts) > 5:
                                aw.qmc.program_t6 = float(parts[5].strip())
                                if len(parts) > 6:
                                    aw.qmc.program_t7 = float(parts[6].strip())
                                    if len(parts) > 7:
                                        aw.qmc.program_t8 = float(parts[7].strip())
                                        if len(parts) > 8:
                                            aw.qmc.program_t9 = float(parts[8].strip())
                                            if len(parts) > 9:
                                                aw.qmc.program_t10 = float(parts[9].strip())
                return tx,float(parts[0].strip()),float(parts[1].strip())
            else:
                return tx,0.,float(output)
        except Exception as e:
            tx = aw.qmc.timeclock.elapsed()/1000.
            _, _, exc_tb = sys.exc_info() 
            aw.qmc.adderror((QApplication.translate("Error Message", "Exception:",None) + " callprogram(): {0} ").format(str(e)),exc_tb.tb_lineno)
            aw.qmc.adderror((QApplication.translate("Error Message", "callprogram() received:",None) + " {0} ").format(str(output)),exc_tb.tb_lineno)
            return tx,0.,0.