Used to signal `asyncio.SubprocessProtocol` of incoming data.
975009
def pipe_data_received(self, fd, data):
        """"""
        if fd == 2:  # stderr fd number
            self._on_stderr(data)
        elif self._on_data:
            self._on_data(data)
        else:
            self._queued_data.append(data)
434538
def run_in_subprocess(func, *args, **kwargs):
    """"""
    from multiprocessing import Process
    thread = Process(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread
599585
def get_cpu_info_json():
	'''
	
	'''

	import json

	output = None

	# If running under pyinstaller, run normally
	if getattr(sys, 'frozen', False):
		info = _get_cpu_info_internal()
		output = json.dumps(info)
		output = "{0}".format(output)
	# if not running under pyinstaller, run in another process.
	# This is done because multiprocesing has a design flaw that
	# causes non main programs to run multiple times on Windows.
	else:
		from subprocess import Popen, PIPE

		command = [sys.executable, __file__, '--json']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]

		if p1.returncode != 0:
			return "{}"

		if not IS_PY2:
			output = output.decode(encoding='UTF-8')

	return output
1325026
def run_as_coroutine(self, stdin, callbacks):
        
        assert isinstance(callbacks, EventLoopCallbacks)

        # Create reader class.
        stdin_reader = PosixStdinReader(stdin.fileno())

        if self.closed:
            raise Exception('Event loop already closed.')

        inputstream = InputStream(callbacks.feed_key)

        try:
            # Create a new Future every time.
            self._stopped_f = asyncio.Future(loop=self.loop)

            # Handle input timouts
            def timeout_handler():
                """
                When no input has been received for INPUT_TIMEOUT seconds,
                flush the input stream and fire the timeout event.
                """
                inputstream.flush()

                callbacks.input_timeout()

            timeout = AsyncioTimeout(INPUT_TIMEOUT, timeout_handler, self.loop)

            # Catch sigwinch
            def received_winch():
                self.call_from_executor(callbacks.terminal_size_changed)

            self.loop.add_signal_handler(signal.SIGWINCH, received_winch)

            # Read input data.
            def stdin_ready():
                data = stdin_reader.read()
                inputstream.feed(data)
                timeout.reset()

                # Quit when the input stream was closed.
                if stdin_reader.closed:
                    self.stop()

            self.loop.add_reader(stdin.fileno(), stdin_ready)

            # Block this coroutine until stop() has been called.
            for f in self._stopped_f:
                yield f

        finally:
            # Clean up.
            self.loop.remove_reader(stdin.fileno())
            self.loop.remove_signal_handler(signal.SIGWINCH)

            # Don't trigger any timeout events anymore.
            timeout.stop()
1220889
def check_output(*args, **kwargs):
    ''''''
    if hasattr(subprocess, 'check_output'):
        return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
                                       *args, **kwargs)
    else:
        process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                   universal_newlines=True, **kwargs)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode:
            error = subprocess.CalledProcessError(retcode, args[0])
            error.output = output
            raise error
        return output
1195597
def _subprocess_method(self, command):
        
        p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.output, self.error = p.communicate()
        self.status = p.returncode
1208802
def signal(signal=None):
    '''
    
    '''
    valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload')

    if signal not in valid_signals:
        return

    # Make sure you use the right arguments
    if signal == "start":
        arguments = ''
    else:
        arguments = ' -s {0}'.format(signal)
    cmd = __detect_os() + arguments
    out = __salt__['cmd.run_all'](cmd)

    # A non-zero return code means fail
    if out['retcode'] and out['stderr']:
        ret = out['stderr'].strip()
    # 'nginxctl configtest' returns 'Syntax OK' to stderr
    elif out['stderr']:
        ret = out['stderr'].strip()
    elif out['stdout']:
        ret = out['stdout'].strip()
    # No output for something like: nginxctl graceful
    else:
        ret = 'Command: "{0}" completed successfully!'.format(cmd)
    return ret
164450
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags):
        
        if use_subprocess is False:
            return foo(*args, **kwrags)

        child_pid = os.fork()
        if child_pid == 0:
            foo(*args, **kwrags)
            sys.exit(0)
        return os.waitpid(child_pid, 0)[1] == 0
1291200
def _async_recv(self):
        """"""

        logging.info("Receive loop started")
        recbuffer = b""

        while not self._stop_event.is_set():
            time.sleep(0.01)
            try:
                recbuffer = recbuffer + self._socket.recv(1024)
                data = recbuffer.split(b'\r\n')
                recbuffer = data.pop()
                if data:
                    for line in data:
                        self._process_data(line.decode(encoding='UTF-8', errors='ignore'))
            except BlockingIOError as e:
                pass
        logging.info("Receive loop stopped")
491604
def _handle_io(self, args, file, result, passphrase=False, binary=False):
        """"""
        p = self._open_subprocess(args, passphrase)
        if not binary:
            stdin = codecs.getwriter(self._encoding)(p.stdin)
        else:
            stdin = p.stdin
        if passphrase:
            _util._write_passphrase(stdin, passphrase, self._encoding)
        writer = _util._threaded_copy_data(file, stdin)
        self._collect_output(p, result, writer, stdin)
        return result
444575
def send_signal(self, s):
        
        self._get_signal_event(s)  # Check if signal has been enabled
        pid = self.get_pid()
        if not pid:
            raise ValueError('Daemon is not running.')
        os.kill(pid, s)
346761
def asynchronous(self, fun, low, user='UNKNOWN', pub=None):
        '''
        
        '''
        async_pub = pub if pub is not None else self._gen_async_pub()

        proc = salt.utils.process.SignalHandlingMultiprocessingProcess(
                target=self._proc_function,
                args=(fun, low, user, async_pub['tag'], async_pub['jid']))
        with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
            # Reset current signals before starting the process in
            # order not to inherit the current signal handlers
            proc.start()
        proc.join()  # MUST join, otherwise we leave zombies all over
        return async_pub
1070906
def __print_async(self, frame_type, headers, body):
        
        if self.__quit:
            return
        if self.verbose:
            self.__sysout(frame_type)
            for k, v in headers.items():
                self.__sysout('%s: %s' % (k, v))
        else:
            if 'message-id' in headers:
                self.__sysout('message-id: %s' % headers['message-id'])
            if 'subscription' in headers:
                self.__sysout('subscription: %s' % headers['subscription'])
        if self.prompt != '':
            self.__sysout('')
        self.__sysout(body)
        if not self.__start:
            self.__sysout(self.prompt, end='')
        else:
            self.__start = False
        self.stdout.flush()
223164
def _process_stdin(self):
        
        with nonblocking(sys.stdin.fileno()):
            data = self._stdin_reader.read()

        # Send input in chunks of 4k.
        step = 4056
        for i in range(0, len(data), step):
            self._send_packet({
                'cmd': 'in',
                'data': data[i:i + step],
            })
191650
def console_output(msg, logging_msg=None):
    """"""
    assert isinstance(msg, bytes)
    assert isinstance(logging_msg, bytes) or logging_msg is None

    from polysh import remote_dispatcher

    remote_dispatcher.log(logging_msg or msg)
    if remote_dispatcher.options.interactive:
        from polysh.stdin import the_stdin_thread
        the_stdin_thread.no_raw_input()
        global last_status_length
        if last_status_length:
            safe_write('\r{}\r'.format(
                last_status_length * ' ').encode())
            last_status_length = 0
    safe_write(msg)
66546
async def two(s: Sublemon):
    """"""
    subprocess_1, subprocess_2 = s.spawn(
        'sleep 1 && echo subprocess 1 in coroutine two',
        'sleep 1 && echo subprocess 2 in coroutine two')
    async for line in amerge(subprocess_1.stdout, subprocess_2.stdout):
        print(line.decode('utf-8'), end='')
1100709
def check_output(self, cmd, timeout=None, keep_rc=False, env=None):
        
        return subproc.call(cmd, timeout=timeout or self.timeout,
                keep_rc=keep_rc, env=env)