Command line interface
522
def main():
    
    parser = argparse.ArgumentParser(
        description='Extract the raw gps communication from an ULog file')
    parser.add_argument('filename', metavar='file.ulg', help='ULog input file')

    def is_valid_directory(parser, arg):
        """Check if valid directory"""
        if not os.path.isdir(arg):
            parser.error('The directory {} does not exist'.format(arg))
        # File exists so return the directory
        return arg
    parser.add_argument('-o', '--output', dest='output', action='store',
                        help='Output directory (default is CWD)',
                        metavar='DIR', type=lambda x: is_valid_directory(parser, x))

    args = parser.parse_args()
    ulog_file_name = args.filename

    msg_filter = ['gps_dump']
    ulog = ULog(ulog_file_name, msg_filter)
    data = ulog.data_list

    output_file_prefix = os.path.basename(ulog_file_name)
    # strip '.ulg'
    if output_file_prefix.lower().endswith('.ulg'):
        output_file_prefix = output_file_prefix[:-4]

    # write to different output path?
    if args.output is not None:
        output_file_prefix = os.path.join(args.output, output_file_prefix)

    to_dev_filename = output_file_prefix+'_to_device.dat'
    from_dev_filename = output_file_prefix+'_from_device.dat'


    if len(data) == 0:
        print("File {0} does not contain gps_dump messages!".format(ulog_file_name))
        exit(0)

    gps_dump_data = data[0]

    # message format check
    field_names = [f.field_name for f in gps_dump_data.field_data]
    if not 'len' in field_names or not 'data[0]' in field_names:
        print('Error: gps_dump message has wrong format')
        exit(-1)

    if len(ulog.dropouts) > 0:
        print("Warning: file contains {0} dropouts".format(len(ulog.dropouts)))

    print("Creating files {0} and {1}".format(to_dev_filename, from_dev_filename))

    with open(to_dev_filename, 'wb') as to_dev_file:
        with open(from_dev_filename, 'wb') as from_dev_file:
            msg_lens = gps_dump_data.data['len']
            for i in range(len(gps_dump_data.data['timestamp'])):
                msg_len = msg_lens[i]
                if msg_len & (1<<7):
                    msg_len = msg_len & ~(1<<7)
                    file_handle = to_dev_file
                else:
                    file_handle = from_dev_file
                for k in range(msg_len):
                    file_handle.write(gps_dump_data.data['data['+str(k)+']'][i])
361262
def main():
    
    command = Command.lookup(args.get(0))

    if len(args) == 0 or args.contains(('-h', '--help', 'help')):
        display_info(args)
        sys.exit(1)

    elif args.contains(('-v', '--version')):
        display_version()
        sys.exit(1)

    elif command:
        arg = args.get(0)
        args.remove(arg)
        command.__call__(command, args)
        sys.exit()

    else:
        show_error(colored.red('Error! Unknown command \'{0}\'.\n'
                               .format(args.get(0))))
        display_info(args)
        sys.exit(1)
159567
def parse_command_line():
    """"""
    parser = argparse.ArgumentParser(
        prog='csp_pulsar_sender',
        description='Send fake pulsar data using ftp protocol.')
    parser.add_argument('config_file', type=argparse.FileType('r'),
                        help='JSON configuration file.')
    parser.add_argument('-v', '--verbose', help='Enable verbose messages.',
                        action='store_true')
    parser.add_argument('-p', '--print_settings', help='Print settings file.',
                        action='store_true')
    return parser.parse_args()
132263
public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");
        FileArgument inputHmlFile = new FileArgument("i", "input-hml-file", "input HML file, default stdin", false);
        FileArgument outputFile = new FileArgument("o", "output-file", "output allele assignment file, default stdout", false);

        ArgumentList arguments = new ArgumentList(about, help, inputHmlFile, outputFile);
        CommandLine commandLine = new CommandLine(args);

        ExtractExpectedHaploids extractExpectedHaploids = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            extractExpectedHaploids = new ExtractExpectedHaploids(inputHmlFile.getValue(), outputFile.getValue());
        }
        catch (CommandLineParseException | IllegalArgumentException e) {
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(extractExpectedHaploids.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
853188
def command_line(argv):
    
    arguments = parse_command_line(argv)
    if arguments.generate:
        generate_fixer_file(arguments.generate)
    paths = edit_files(arguments.patterns,
                       expressions=arguments.expressions,
                       functions=arguments.functions,
                       executables=arguments.executables,
                       start_dirs=arguments.start_dirs,
                       max_depth=arguments.max_depth,
                       dry_run=arguments.dry_run,
                       output=arguments.output,
                       encoding=arguments.encoding,
                       newline=arguments.newline)
    # If the output is not sys.stdout, we need to close it because
    # argparse.FileType does not do it for us.
    is_sys = arguments.output in [sys.stdout, sys.stderr]
    if not is_sys and isinstance(arguments.output, io.IOBase):
        arguments.output.close()
    return paths
1008278
def cli():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('api', help="""
        API to call.
        One one of 'article', 'frontpage', 'product', 'image', 'analyze', or
        'discussion'.
    """)
    parser.add_argument('url', help="""
        URL to pass as the 'url' parameter.
    """)
    parser.add_argument('token', help="""
        API key (token).
        Get one at https://www.diffbot.com/.
    """)
    parser.add_argument('-a', '--all', help="""
        Request all fields.
    """, action='store_true')
    parser.add_argument('-f', '--file', help="""
        File to read data from.
        Use '-' to read from STDIN.
    """)
    fields = text = html = None
    _args = parser.parse_args()
    if _args.all:
        fields = '*'
    if _args.file == '-':
        text = sys.stdin.read()
    elif _args.file:
        with open(_args.file, 'rb') as src:
            if os.path.splitext(_args.file)[1] in ('.html', '.htm'):
                html = src.read().decode(ENCODING)
            else:
                text = src.read().decode(ENCODING)
    print(json.dumps((api(_args.api, _args.url, _args.token,
                          html=html or None,
                          text=text or None,
                          fields=fields)),
                     sort_keys=True,
                     indent=2))
1289528
def _cmdline(argv=None):
    
    parser = ArgumentParser()
    parser.add_argument("-c", "--config", action="append",
            help="config file [etc/config.yml]")
    parser.add_argument("-v", "--version", action="version",
            version="pipsort {:s}".format(__version__),
            help="print version and exit")
    parser.add_argument("-w", "--warn", default="WARNING",
            help="logger warning level [WARNING]")
    parser.add_argument("search_term", type=str,
                        help="Search term for PyPI")
    args = parser.parse_args(argv)
    if not args.config:
        args.config = ["etc/config.yml"]
    return args
779649
def command_line_runner():
    """"""
    parser = get_parser()
    args = vars(parser.parse_args())
    if args['version']:
        print(__version__)
        return
    if args['clear_cache']:
        utils.clear_cache()
        print('Cleared {0}.'.format(utils.CACHE_DIR))
        return
    if not args['query']:
        parser.print_help()
        return

    # Enable cache unless user sets environ variable SCRAPE_DISABLE_CACHE
    if not os.getenv('SCRAPE_DISABLE_CACHE'):
        utils.enable_cache()

    # Save images unless user sets environ variable SCRAPE_DISABLE_IMGS
    if os.getenv('SCRAPE_DISABLE_IMGS'):
        args['no_images'] = True

    # Prompt user for filetype if none specified
    prompt_filetype(args)

    # Prompt user to save images when crawling (for pdf and HTML formats)
    prompt_save_images(args)

    # Scrape webpage content
    scrape(args)
1216869
def main(args=None):
    """"""
    parser = argparse.ArgumentParser(
        description='Fritz!Box Smarthome CLI tool.')
    parser.add_argument('-v', action='store_true', dest='verbose',
                        help='be more verbose')
    parser.add_argument('-f', '--fritzbox', type=str, dest='host',
                        help='Fritz!Box IP address', default='fritz.box')
    parser.add_argument('-u', '--user', type=str, dest='user',
                        help='Username')
    parser.add_argument('-p', '--password', type=str, dest='password',
                        help='Username')
    parser.add_argument('-a', '--ain', type=str, dest='ain',
                        help='Actor Identification', default=None)
    parser.add_argument('-V', '--version', action='version',
                        version='{version}'.format(version=__version__),
                        help='Print version')

    _sub = parser.add_subparsers(title='Commands')

    # list all devices
    subparser = _sub.add_parser('list', help='List all available devices')
    subparser.set_defaults(func=list_all)

    # device
    subparser = _sub.add_parser('device', help='Device/Actor commands')
    _sub_switch = subparser.add_subparsers()

    # device name
    subparser = _sub_switch.add_parser('name', help='get the device name')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_name)

    # device presence
    subparser = _sub_switch.add_parser('present',
                                       help='get the device presence')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_presence)

    # device stats
    subparser = _sub_switch.add_parser('stats',
                                       help='get the device statistics')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_statistics)

    # switch
    subparser = _sub.add_parser('switch', help='Switch commands')
    _sub_switch = subparser.add_subparsers()

    # switch get
    subparser = _sub_switch.add_parser('get', help='get state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_get)

    # switch on
    subparser = _sub_switch.add_parser('on', help='set on state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_on)

    # switch off
    subparser = _sub_switch.add_parser('off', help='set off state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_off)

    # switch toggle
    subparser = _sub_switch.add_parser('toggle', help='set off state')
    subparser.add_argument('ain', type=str, metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_toggle)

    args = parser.parse_args(args)

    logging.basicConfig()
    if args.verbose:
        logging.getLogger('pyfritzhome').setLevel(logging.DEBUG)

    fritzbox = None
    try:
        fritzbox = Fritzhome(host=args.host, user=args.user,
                             password=args.password)
        fritzbox.login()
        args.func(fritzbox, args)
    finally:
        if fritzbox is not None:
            fritzbox.logout()
1301001
def interface(self):
        
        
        # Possible control arguments
        controls = {
            'start': self.do_start,
            'stop': self.do_stop,
            'status': self.do_status,
            'restart': self.do_restart,
            'reload': self.do_restart    
        }
        
        # Process the control argument
        try:
            controls[self.command]()
        except KeyError:
            self.write_stdout('Usage: {} {{start|stop|status|restart|reload}}'.format(self.name), 3)
        exit(0)
421200
public static void main(String[] args) {
        Settings settings = new Settings();
        new JCommander(settings, args);

        if (!settings.isGuiSupressed()) {
            OkapiUI okapiUi = new OkapiUI();
            okapiUi.setVisible(true);
        } else {
            int returnValue;
            
            returnValue = commandLine(settings);
            
            if (returnValue != 0) {
                System.out.println("An error occurred");
            }
        }
    }
218578
def main(args=None, prog=None):
    """"""
    args = args if args is not None else sys.argv[1:]
    prog = prog if prog is not None else sys.argv[0]
    # Prevent broken pipe exception from being raised.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
    p = argparse.ArgumentParser(prog=prog)
    p.add_argument('-o', '--output', metavar='PATH',
                   type=argparse.FileType('w'), default=sys.stdout,
                   help='Write output to PATH')
    p.add_argument('--api', help='Match API', default=None)
    p.add_argument('--profile', help='Match profile', default=None)
    p.add_argument('--support', default=None,
                   help='Match extension support string')
    g = p.add_mutually_exclusive_group()
    g.add_argument('--list-apis', action='store_true', dest='list_apis',
                   help='List apis in registry', default=False)
    g.add_argument('--list-profiles', action='store_true', default=False,
                   dest='list_profiles', help='List profiles in registry')
    g.add_argument('--list-supports', action='store_true',
                   dest='list_supports', default=False,
                   help='List extension support strings')
    p.add_argument('registry', type=argparse.FileType('rb'), nargs='?',
                   default=stdin, help='Registry path')
    args = p.parse_args(args)
    o = args.output
    try:
        registry = load(args.registry)
        if args.list_apis:
            for x in sorted(registry.get_apis()):
                print(x, file=o)
            return 0
        elif args.list_profiles:
            for x in sorted(registry.get_profiles()):
                print(x, file=o)
            return 0
        elif args.list_supports:
            for x in sorted(registry.get_supports()):
                print(x, file=o)
            return 0
        apis = group_apis(registry, None, None, args.api, args.profile,
                          args.support)
        for api in apis:
            print('#ifndef', api.name, file=o)
            print('#define', api.name, file=o)
            print(api.text, file=o)
            print('#endif', file=o)
            print('', file=o)
    except:
        e = sys.exc_info()[1]
        print(prog, ': error: ', e, sep='', file=sys.stderr)
        return 1
    return 0
191117
def main():
    """"""
    # Setup logging for the command line
    name = os.path.splitext(os.path.basename(__file__))[0]
    logging.basicConfig(
        format="%(asctime)s [%(process)s] %(levelname)s {} - %(message)s".format(name),
        level=logging.INFO)

    # Program arguments
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--edges", metavar="FILENAME", required=True,
                        help="input network edges file in TSV format")
    parser.add_argument("--output-clusters", metavar="FILENAME", required=True,
                        help="output clusters file in JSON format")
    parser.add_argument("--oslom-output", metavar="DIRECTORY", required=True,
                        help="output directory for OSLOM files")
    parser.add_argument("--min-cluster-size", metavar="INTEGER", type=int,
                        default=DEF_MIN_CLUSTER_SIZE,
                        help="minimum cluster size (default: %(default)s)")
    parser.add_argument("--oslom-exec", metavar="EXECUTABLE",
                        default=DEF_OSLOM_EXEC,
                        help="OSLOM executable program to use "
                             "(default: %(default)s)")
    parser.add_argument("oslom_args", metavar="OSLOM_ARG", nargs="*",
                        default=DEF_OSLOM_ARGS,
                        help="argument to pass to OSLOM (don't pass '-f' !) "
                             "(default: %(default)s)")

    # Run OSLOM with parsed arguments
    sys.exit(not run(parser.parse_args()))
746212
def text_ui(self):
        
        self.logger.info("Starting command line interface")
        self.help()
        try:
            self.ipython_ui()
        except ImportError:
            self.fallback_ui()
        self.system.cleanup()
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
532814
def main():
    """""""
    parser = argparse.ArgumentParser(description='Do something awesome')
    parser.add_argument('input_list', nargs='+',
                        type=str, default=sys.stdin)
    parser.add_argument('-o', '--outfile', nargs='?',
                        type=argparse.FileType('w'), default=sys.stdout)
    args = parser.parse_args()

    input_list = args.input_list
    print '\n'.join(get_ips_from_cidr_subnets(input_list))
469418
public static void main(final String... args) {

        // Configure command line options
        final Options options = new Options();
        options.addOption("c", "config", true, "use service configuration file / classpath "
                + "resource (default '" + DEFAULT_CONFIG + "')");
        options.addOption("v", "version", false,
                "display version and copyright information, then exit");
        options.addOption("h", "help", false, "display usage information, then exit");

        // Initialize exit status
        int status = EX_OK;

        try {
            // Parse command line and handle different commands
            final CommandLine cmd = new GnuParser().parse(options, args);
            if (cmd.hasOption("v")) {
                // Show version and copyright (http://www.gnu.org/prep/standards/standards.html)
                System.out.println(String.format(
                        "%s (FBK KnowledgeStore) %s\njava %s bit (%s) %s\n%s", PROGRAM_EXECUTABLE,
                        PROGRAM_VERSION, System.getProperty("sun.arch.data.model"),
                        System.getProperty("java.vendor"), System.getProperty("java.version"),
                        PROGRAM_DISCLAIMER));

            } else if (cmd.hasOption("h")) {
                // Show usage (done later) and terminate
                status = EX_USAGE;

            } else {
                // Run the service. Retrieve the configuration
                final String configLocation = cmd.getOptionValue('c', DEFAULT_CONFIG);

                // Differentiate between normal run, commons-daemon start, commons-daemon stop
                if (cmd.getArgList().contains("__start")) {
                    start(configLocation); // commons-daemon start
                } else if (cmd.getArgList().contains("__stop")) {
                    stop(); // commons-deamon stop
                } else {
                    run(configLocation); // normal execution
                }
            }

        } catch (final ParseException ex) {
            // Display error message and then usage on syntax error
            System.err.println("SYNTAX ERROR: " + ex.getMessage());
            status = EX_USAGE;

        } catch (final ServiceConfigurationError ex) {
            // Display error message and stack trace and terminate on configuration error
            System.err.println("INVALID CONFIGURATION: " + ex.getMessage());
            Throwables.getRootCause(ex).printStackTrace();
            status = EX_CONFIG;

        } catch (final Throwable ex) {
            // Display error message and stack trace on generic error
            System.err.print("EXECUTION FAILED: ");
            ex.printStackTrace();
            status = ex instanceof IOException ? EX_IOERR : EX_UNAVAILABLE;
        }

        // Display usage information if necessary
        if (status == EX_USAGE) {
            final PrintWriter out = new PrintWriter(System.out);
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printUsage(out, WIDTH, PROGRAM_EXECUTABLE, options);
            if (PROGRAM_DESCRIPTION != null) {
                formatter.printWrapped(out, WIDTH, "\n" + PROGRAM_DESCRIPTION.trim());
            }
            out.println("\nOptions");
            formatter.printOptions(out, WIDTH, options, 2, 2);
            out.flush();
        }

        // Display exit status for convenience
        if (status != EX_OK) {
            System.err.println("[exit status: " + status + "]");
        } else {
            System.out.println("[exit status: " + status + "]");
        }

        // Flush STDIN and STDOUT before exiting (we noted truncated outputs otherwise)
        System.out.flush();
        System.err.flush();

        // Force exiting (in case there are threads still running)
        System.exit(status);
    }