Start Crossbar.io in a subprocess.
162553
def start(self):
        
        if self.started is True:
            raise WampyError("Router already started")

        # will attempt to connect or start up the CrossBar
        crossbar_config_path = self.config_path
        cbdir = self.crossbar_directory

        # starts the process from the root of the test namespace
        cmd = [
            'crossbar', 'start',
            '--cbdir', cbdir,
            '--config', crossbar_config_path,
        ]

        self.proc = subprocess.Popen(cmd, preexec_fn=os.setsid)

        self._wait_until_ready()
        logger.info(
            "Crosbar.io is ready for connections on %s (IPV%s)",
            self.url, self.ipv
        )

        self.started = True
123475
def main(argv=None, loop=SharedLoop, max_time=None):
    """"""
    should_raise = argv is not None

    if argv is None:
        argv = sys.argv[1:]

    parser = build_parser()
    cmd_args = parser.parse_args(argv)

    configure_logging(cmd_args.verbose)
    logger = logging.getLogger(__name__)

    try:
        args = {}
        if cmd_args.config is not None:
            try:
                with open(cmd_args.config, "r") as conf:
                    args = json.load(conf)
            except IOError as exc:
                raise ScriptError("Could not open config file %s due to %s"
                                  % (cmd_args.config, str(exc)), 2)
            except ValueError as exc:
                raise ScriptError("Could not parse JSON from config file %s due to %s"
                                  % (cmd_args.config, str(exc)), 3)
            except TypeError as exc:
                raise ScriptError("You must pass the path to a json config file", 4)

        logger.critical("Starting gateway")

        gateway = IOTileGateway(args, loop=loop)
        loop.run_coroutine(gateway.start())

        logger.critical("Gateway running")

        # Run forever until we receive a ctrl-c
        # (allow quitting early after max_time seconds for testing)
        loop.wait_for_interrupt(max_time=max_time)

        loop.run_coroutine(gateway.stop())
    except ScriptError as exc:
        if should_raise:
            raise exc

        logger.fatal("Quitting due to error: %s", exc.msg)
        return exc.code
    except Exception as exc:  # pylint: disable=W0703
        if should_raise:
            raise exc

        logger.exception("Fatal error running gateway")
        return 1

    return 0
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
497356
def main():
    
    # Catch the CTRL-C signal
    signal.signal(signal.SIGINT, __signal_handler)

    # Log Glances and psutil version
    logger.info('Start Glances {}'.format(__version__))
    logger.info('{} {} and psutil {} detected'.format(
        platform.python_implementation(),
        platform.python_version(),
        psutil_version))

    # Share global var
    global core

    # Create the Glances main instance
    core = GlancesMain()
    config = core.get_config()
    args = core.get_args()

    # Glances can be ran in standalone, client or server mode
    start(config=config, args=args)
1100578
def start(self, start_loop=True):
        
        txaio.start_logging()
        runner = self.setup_runner()
        if start_loop:
            try:
                runner.run(Component)
            except EventifyHandlerInitializationFailed as initError:
                logging.error('Unable to initialize handler: %s.' % initError.message)
                sys.exit(1)
            except ConnectionRefusedError:
                logging.error('Unable to connect to crossbar instance. Is it running?')
                sys.exit(1)
            except KeyboardInterrupt:
                logging.info('User initiated shutdown')
                loop = asyncio.get_event_loop()
                loop.stop()
                sys.exit(1)
            self.check_event_loop()
            self.reconnect()
        else:
            return runner.run(
                Component,
                start_loop=start_loop
            )
69088
def run_app(self):
        """"""
        # Update system arguments
        sys.argv[0] = sys.executable
        sys.argv[1] = '{}.py'.format(sys.argv[1])

        # Make sure to exit with the return value from the subprocess call
        self._app_process = subprocess.Popen(sys.argv)
        return self._app_process.wait()
977594
def start(self):
        """"""
        c_out, c_err = (open(self.path('cmd.stdout'), 'w'),
                        open(self.path('cmd.stderr'), 'w'))
        kw = self.kw.copy()
        kw['stdout'] = c_out
        kw['stderr'] = c_err
        if not kw.get('cwd', None):
            kw['cwd'] = os.getcwd()
        pr = subprocess.Popen(self.cmd_args, **kw)
        with open(self.path('cmd.pid'), 'w') as f:
            f.write(str(pr.pid))
1063368
def get_process(cmd):
    """"""

    if sys.platform.startswith('win'):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        process = subprocess.Popen(
            cmd,
            startupinfo=startupinfo,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            stdin=subprocess.PIPE,
            shell=False
        )
    else:
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            stdin=subprocess.PIPE,
            shell=False
        )
    return process
393949
def run_system_command(self, command):
        
        def wait_for_enter():
            """
            Create a sub application to wait for the enter key press.
            This has two advantages over using 'input'/'raw_input':
            - This will share the same input/output I/O.
            - This doesn't block the event loop.
            """
            from .shortcuts import create_prompt_application

            registry = Registry()

            @registry.add_binding(Keys.ControlJ)
            @registry.add_binding(Keys.ControlM)
            def _(event):
                event.cli.set_return_value(None)

            application = create_prompt_application(
                message='Press ENTER to continue...',
                key_bindings_registry=registry)
            self.run_sub_application(application)

        def run():
            # Try to use the same input/output file descriptors as the one,
            # used to run this application.
            try:
                input_fd = self.input.fileno()
            except AttributeError:
                input_fd = sys.stdin.fileno()
            try:
                output_fd = self.output.fileno()
            except AttributeError:
                output_fd = sys.stdout.fileno()

            # Run sub process.
            # XXX: This will still block the event loop.
            p = Popen(command, shell=True,
                      stdin=input_fd, stdout=output_fd)
            p.wait()

            # Wait for the user to press enter.
            wait_for_enter()

        self.run_in_terminal(run)
95164
async def open(
        self,
        cmd: List[str],
        input_source: Optional[str],
        output: Optional[str] = "-",
        extra_cmd: Optional[str] = None,
        stdout_pipe: bool = True,
        stderr_pipe: bool = False,
    ) -> bool:
        """"""
        stdout = subprocess.PIPE if stdout_pipe else subprocess.DEVNULL
        stderr = subprocess.PIPE if stderr_pipe else subprocess.DEVNULL

        if self.is_running:
            _LOGGER.warning("FFmpeg is already running!")
            return True

        # set command line
        self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)

        # start ffmpeg
        _LOGGER.debug("Start FFmpeg with %s", str(self._argv))
        try:
            proc_func = functools.partial(
                subprocess.Popen,
                self._argv,
                bufsize=0,
                stdin=subprocess.PIPE,
                stdout=stdout,
                stderr=stderr,
            )
            self._proc = await self._loop.run_in_executor(None, proc_func)
        except Exception as err:  # pylint: disable=broad-except
            _LOGGER.exception("FFmpeg fails %s", err)
            self._clear()
            return False

        return self._proc is not None
968866
def start(path=None, host=None, port=None, color=None, cors=None, detach=False, nolog=False):
    """"""
    if detach:
        sys.argv.append('--no-log')
        idx = sys.argv.index('-d')
        del sys.argv[idx]
        cmd = sys.executable + ' ' + ' '.join([sys.argv[0], 'start'] + sys.argv[1:])
        if os.name == 'nt':
            cmd = 'start /B %s' % cmd
        else:
            cmd = '%s &' % cmd
        os.system(cmd)
    else:    
        if path:
            path = os.path.abspath(path)
        app.config['PATH_HTML']= first_value(path, app.config.get('PATH_HTML',None), os.getcwd())
        app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0')
        app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001))
        app.logger.setLevel(logging.DEBUG)
        app.config['historylog'] = HistoryHandler()
        app.logger.addHandler(app.config['historylog'])
        if not nolog:
            app.logger.addHandler(StreamHandler())
        if cors: CORS(app)
        app.run(host = app.config['HOST'],
                port = app.config['PORT'],
                threaded = True)
1195896
async def execute_process(*cmd, log=None, loop=None):
    '''
    

    '''
    p = await asyncio.create_subprocess_exec(
        *cmd,
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        loop=loop)
    stdout, stderr = await p.communicate()
    if log:
        log.debug("Exec %s -> %d", cmd, p.returncode)
        if stdout:
            log.debug(stdout.decode('utf-8'))
        if stderr:
            log.debug(stderr.decode('utf-8'))
    return p.returncode == 0
587483
def _execute_wk(*args, input=None):
    
    wk_args = (WK_PATH,) + args
    return subprocess.run(wk_args, input=input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
825510
def main(argv=None, apply_config=True):
    """"""
    if argv is None:
        argv = sys.argv

    try:
        # Exit on broken pipe.
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    except AttributeError:  # pragma: no cover
        # SIGPIPE is not available on Windows.
        pass

    try:
        args = parse_args(argv[1:], apply_config=apply_config)

        if args.list_fixes:
            for code, description in sorted(supported_fixes()):
                print('{code} - {description}'.format(
                    code=code, description=description))
            return 0

        if args.files == ['-']:
            assert not args.in_place

            encoding = sys.stdin.encoding or get_encoding()

            # LineEndingWrapper is unnecessary here due to the symmetry between
            # standard in and standard out.
            wrap_output(sys.stdout, encoding=encoding).write(
                fix_code(sys.stdin.read(), args, encoding=encoding))
        else:
            if args.in_place or args.diff:
                args.files = list(set(args.files))
            else:
                assert len(args.files) == 1
                assert not args.recursive

            fix_multiple_files(args.files, args, sys.stdout)
    except KeyboardInterrupt:
        return 1
388867
def main(argv=None, loop=SharedLoop):
    """"""

    if argv is None:
        argv = sys.argv[1:]

    list_parser = argparse.ArgumentParser(add_help=False)
    list_parser.add_argument('-l', '--list', action='store_true', help="List all known installed interfaces and devices and then exit")
    list_parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")

    parser = argparse.ArgumentParser(description="Serve acess to a virtual IOTile device using a virtual IOTile interface")

    parser.add_argument('interface', help="The name of the virtual device interface to use")
    parser.add_argument('device', help="The name of the virtual device to create")
    parser.add_argument('-c', '--config', help="An optional JSON config file with arguments for the interface and device")
    parser.add_argument('-l', '--list', action='store_true', help="List all known installed interfaces and devices and then exit")
    parser.add_argument('-n', '--scenario', help="Load a test scenario from the given file")
    parser.add_argument('-s', '--state', help="Load a given state into the device before starting to serve it.  Only works with emulated devices.")
    parser.add_argument('-d', '--dump', help="Dump the device's state when we exit the program.  Only works with emulated devices.")
    parser.add_argument('-t', '--track', help="Track all changes to the device's state.  Only works with emulated devices.")
    parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")

    args, _rest = list_parser.parse_known_args(argv)

    if args.list:
        configure_logging(args.verbose)

        reg = ComponentRegistry()
        print("Installed Device Servers:")
        for name, _iface in reg.load_extensions('iotile.device_server', class_filter=AbstractDeviceServer):
            print('- {}'.format(name))

        print("\nInstalled Virtual Devices:")
        for name, dev in reg.load_extensions('iotile.virtual_device', class_filter=VirtualIOTileDevice,
                                             product_name="virtual_device"):
            print('- {}: {}'.format(name, one_line_desc(dev)))

        return 0

    args = parser.parse_args(argv)

    configure_logging(args.verbose)

    config = {}
    if args.config is not None:
        with open(args.config, "r") as conf_file:
            config = json.load(conf_file)

    started = False
    device = None
    stop_immediately = args.interface == 'null'
    try:
        server = instantiate_interface(args.interface, config, loop)
        device = instantiate_device(args.device, config, loop)

        if args.state is not None:
            print("Loading device state from file %s" % args.state)
            device.load_state(args.state)

        if args.scenario is not None:
            print("Loading scenario from file %s" % args.scenario)

            with open(args.scenario, "r") as infile:
                scenario = json.load(infile)

            # load_metascenario expects a list of scenarios even when there is only one
            if isinstance(scenario, dict):
                scenario = [scenario]

            device.load_metascenario(scenario)

        if args.track is not None:
            print("Tracking all state changes to device")
            device.state_history.enable()

        adapter = VirtualDeviceAdapter(devices=[device], loop=loop)
        server.adapter = adapter

        loop.run_coroutine(adapter.start())

        try:
            loop.run_coroutine(server.start())
        except:
            loop.run_coroutine(adapter.stop())
            adapter = None
            raise

        started = True

        print("Starting to serve virtual IOTile device")

        if stop_immediately:
            return 0

        # We need to periodically process events that are queued up in the interface
        while True:
            time.sleep(0.5)

    except KeyboardInterrupt:
        print("Break received, cleanly exiting...")
    finally:
        if args.dump is not None and device is not None:
            print("Dumping final device state to %s" % args.dump)
            device.save_state(args.dump)

        if started:
            loop.run_coroutine(server.stop())
            loop.run_coroutine(adapter.stop())

        if args.track is not None and device is not None:
            print("Saving state history to file %s" % args.track)
            device.state_history.dump(args.track)

    return 0
929221
def spawn(argv, master_read=_read, stdin_read=_read):
    """"""
    if type(argv) == type(''):
        argv = (argv,)
    pid, master_fd = fork()
    if pid == CHILD:
        try:
            os.execlp(argv[0], *argv)
        except:
            # If we wanted to be really clever, we would use
            # the same method as subprocess() to pass the error
            # back to the parent.  For now just dump stack trace.
            traceback.print_exc()
        finally:
            os._exit(1)
    try:
        mode = tty.tcgetattr(STDIN_FILENO)
        tty.setraw(STDIN_FILENO)
        restore = 1
    except tty.error:    # This is the same as termios.error
        restore = 0
    try:
        _copy(master_fd, master_read, stdin_read)
    except OSError:
        # Some OSes never return an EOF on pty, just raise
        # an error instead.
        pass
    finally:
        if restore:
            tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)

    os.close(master_fd)
    return os.waitpid(pid, 0)[1]
464774
def run(self):
        '''
        
        '''
        if not len(self.netapi):
            log.error("Did not find any netapi configurations, nothing to start")

        kwargs = {}
        if salt.utils.platform.is_windows():
            kwargs['log_queue'] = salt.log.setup.get_multiprocessing_logging_queue()
            kwargs['log_queue_level'] = salt.log.setup.get_multiprocessing_logging_level()

        for fun in self.netapi:
            if fun.endswith('.start'):
                log.info('Starting %s netapi module', fun)
                self.process_manager.add_process(
                    RunNetapi,
                    args=(self.opts, fun),
                    kwargs=kwargs,
                    name='RunNetapi'
                )

        # Install the SIGINT/SIGTERM handlers if not done so far
        if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
            # No custom signal handling was added, install our own
            signal.signal(signal.SIGINT, self._handle_signals)

        if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
            # No custom signal handling was added, install our own
            signal.signal(signal.SIGTERM, self._handle_signals)

        self.process_manager.run()