Exemple #1
0
def Exec(argv,limit=None,pp=None,RootDir=None):
    ret=[False,None,None,None]
    si= win32process.GetStartupInfo()
    if pp:
        si.hStdInput=pp[0]
        si.hStdOutput=pp[1]
        si.hStdError=pp[2]

    si.wShowWindow=win32con.SW_HIDE
    si.dwFlags = win32process.STARTF_USESHOWWINDOW | win32con.STARTF_USESTDHANDLES
    cmd=" ".join(argv)
    win32api.SetLastError(0)
    #PyHANDLE, PyHANDLE, int, int = CreateProcess(appName, commandLine , processAttributes , threadAttributes , bInheritHandles , dwCreationFlags , newEnvironment , currentDirectory , startupinfo )
    try:
        pi= win32process.CreateProcess(None,cmd,None,None,True,win32con.CREATE_SUSPENDED,None,RootDir,si)
    except pywintypes.error , e:
        ret[1]=e[2]
        return ret
Exemple #2
0
    def _startCsoundOnMSW(self, cmd):
        """
        Wrapper for _startCsound on Windows plattforms
        
        @type cmd: string
        @param cmd: Commando for the csound process.
        """
        import win32process
        
        si = win32process.GetStartupInfo()
        si.dwFlags = 0
        si.hStdInput = None
        si.hStdOutput = None
        si.hStdError = None
        
        procArgs = (None,  # appName
                    cmd,  # commandLine
                    None,  # processAttributes
                    None,  # threadAttributes
                    1,  # bInheritHandles
                    0, # dwCreationFlags
                    None,  # newEnvironment
                    None,  # currentDirectory
                    si)  # startupinfo
        processHandle, threadHandle, pid, tid  = win32process.CreateProcess(*procArgs)
        threadHandle.Close()

        self._handle = processHandle
        self._pid = pid
        
        # Timeout for feedback on the succes of the csound process
        timeOut = float(self.config.getVal(tools.config.Csound.FEEDBACK_TIMEOUT)) / 1000.0
        import time
        time.sleep(timeOut)
        
        return win32process.GetExitCodeProcess(self._handle) == 259
Exemple #3
0
    def startChild(self, args, env):
        '''Start the console process.

        startChild() starts the console process with arguments to command it to create the read
        child process. startChild() does not connect to console, it just creates it.

        The console creation depends on if the host process is running in a normal python process,
        or in a PyInstaller bundle.
        '''

        # startupinfo for Windows' CreateProcess.
        si = win32process.GetStartupInfo()
        si.dwFlags = win32process.STARTF_USESHOWWINDOW
        if not self.interact_state:
            si.wShowWindow = win32con.SW_HIDE

        # collect arguments for console
        self.console_class_parameters.update({
            'console_reader_class': self.console_class_name,
            'host_pid': self.host_pid,
            'local_echo': self.echo,
            'interact': self.interact_state,
            'codepage': self.codepage
        })
        console_class_parameters_kv_pairs = [
            f'--{k}={v}' for k, v in self.console_class_parameters.items()
            if v is not None
        ]
        console_class_parameters_str = ' '.join(
            console_class_parameters_kv_pairs)
        args_str = join_args(args)
        console_args = f" {console_class_parameters_str} -- {args_str}"

        # set environment variables for the console
        # Deep copy needed to prevent cycle-to-cycle growth. See #31 for more details.
        environ = os.environ.copy()

        if getattr(sys, 'frozen', False):  # pragma: no cover
            '''Runing in a PyInstaller bundle:
            Pyinstaller has no explicit python interpreter, so console-reader should be bundled
            also, and host should call it as a windows executable.

            This code cannot be covered during tests, because it runs only in bundled way.

            https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#using-sys-executable-and-sys-argv-0
            https://github.com/pyinstaller/pyinstaller/issues/822
            '''

            if not hasattr(sys, '_MEIPASS'):
                raise Exception(
                    '`sys.frozen` found, but `sys._MEIPASS` not. Only pyinstaller is supported.'
                )
            dirname = os.path.dirname(sys.executable)

            console_executable = os.path.join(dirname, '..', 'wexpect',
                                              'wexpect.exe')
            commandLine = f'"{console_executable}" {console_args}'

        else:
            '''Runing in a normal python process
            '''
            dirname = os.path.dirname(os.path.abspath(__file__))
            spath = [os.path.dirname(dirname)]

            pyargs = ['-m']
            python_executable = sys.executable

            if self.coverage_console_reader:
                pyargs = ['-m', 'coverage', 'run', '--parallel-mode', '-m']

            # add current location to PYTHONPATH environment variable to be able to start the child.
            python_path = environ.get('PYTHONPATH', '')
            spath = ';'.join(spath)
            environ['PYTHONPATH'] = f'{spath};{python_path}'

            child_class_initializator = f"wexpect {console_args}"

            pyargs = ' '.join(pyargs)
            commandLine = f'"{python_executable}" {pyargs} {child_class_initializator}'

        logger.info(f'Console starter command:{commandLine}')

        # start the console-reader
        _, _, self.console_pid, __otid = win32process.CreateProcess(
            None, commandLine, None, None, False,
            win32process.CREATE_NEW_CONSOLE, environ, self.cwd, si)
Exemple #4
0
    def __init__(self,
                 path,
                 host_pid,
                 codepage=None,
                 window_size_x=80,
                 window_size_y=25,
                 buffer_size_x=80,
                 buffer_size_y=16000,
                 local_echo=True,
                 interact=False,
                 **kwargs):
        """Initialize the console starts the child in it and reads the console periodically.

        Args:
            path (str): Child's executable with arguments.
            parent_pid (int): Parent (aka. host) process process-ID
            codepage (:obj:, optional): Output console code page.
        """
        self.lastRead = 0
        self.__bufferY = 0
        self.lastReadData = ""
        self.totalRead = 0
        self.__buffer = StringIO()
        self.__currentReadCo = win32console.PyCOORDType(0, 0)
        self.pipe = None
        self.connection = None
        self.consin = None
        self.consout = None
        self.local_echo = local_echo
        self.console_pid = os.getpid()
        self.host_pid = host_pid
        self.host_process = psutil.Process(host_pid)
        self.child_process = None
        self.child_pid = None
        self.enable_signal_chars = True

        logger.info(
            f'ConsoleReader started. location {os.path.abspath(__file__)}')

        if codepage is None:
            codepage = windll.kernel32.GetACP()

        try:
            logger.info("Setting console output code page to %s" % codepage)
            win32console.SetConsoleOutputCP(codepage)
            logger.info("Console output code page: %s" %
                        ctypes.windll.kernel32.GetConsoleOutputCP())
        except Exception as e:  # pragma: no cover
            # I hope this code is unreachable...
            logger.error(e)

        try:
            self.create_connection(**kwargs)
            logger.info('Spawning %s' % path)
            try:
                self.initConsole()
                si = win32process.GetStartupInfo()
                self.__childProcess, _, self.child_pid, self.child_tid = win32process.CreateProcess(
                    None, path, None, None, False, 0, None, None, si)
                self.child_process = psutil.Process(self.child_pid)

                logger.info(
                    f'Child pid: {self.child_pid}  Console pid: {self.console_pid}'
                )

            except Exception:  # pragma: no cover
                # I hope this code is unreachable...
                logger.error(traceback.format_exc())
                return

            if interact:
                self.interact()
                self.interact()

            self.read_loop()
        except Exception:  # pragma: no cover
            # I hope this code is unreachable...
            logger.error(traceback.format_exc())
        finally:
            try:
                self.terminate_child()
                time.sleep(.01)
                self.send_to_host(self.readConsoleToCursor())
                self.sendeof()
                time.sleep(.1)
                self.close_connection()
                logger.info('Console finished.')
            except Exception:  # pragma: no cover
                # I hope this code is unreachable...
                logger.error(traceback.format_exc())