Python os 模块,EX_USAGE 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用os.EX_USAGE

项目:redisrwlock    作者:veshboo    | 项目源码 | 文件源码
def test_option_repeat_interval(self):
        """test --retry and --interval options"""
        # run with --retry, see 2 lines, then kill -INT
        cmd, output = runCmdOutput(['-p', '7788', '-r'],
                                   wait=False, limit=2)
        cmd.send_signal(signal.SIGINT)
        self.assertEqual(cmd.wait(), 1)
        cmd.stdout.close()
        # run with --retry, see 4 lines, then kill -INT
        cmd, output = runCmdOutput(['-p', '7788', '-r', '-i', '1'],
                                   wait=False, limit=4)
        cmd.send_signal(signal.SIGINT)
        self.assertEqual(cmd.wait(), 1)
        cmd.stdout.close()
        # invalid --interval option argument (int > 0)
        cmd, output = runCmdOutput(['-p', '7788', '-i', '0'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
        # --interval option argument ignored if no --retry
        cmd, output = runCmdOutput(['-p', '7788', '-i', '1000'])
        self.assertEqual(cmd.returncode, os.EX_OK)
项目:thefuzz    作者:droberson    | 项目源码 | 文件源码
def __init__(self, server, port):
        self.server = server
        self.port = port
        self.fuzz_queue = Queue.Queue()
        self.header = None

        # Validate IP address
        try:
            socket.inet_aton(server)
        except socket.error:
            print "[-] Invalid IP address: %s" % server
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Validate port number
        if port > 65535 or port < 1:
            print "[-] Invalid port number: %d" % port
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Create client socket
        self.client = None
项目:pyrate-build    作者:pyrate-build    | 项目源码 | 文件源码
def main():
    version_info = 'pyrate version ' + __version__
    try:
        if os.environ.get('TESTOLDIMPORTS'):
            raise ImportError()
        import argparse
        parser = argparse.ArgumentParser()
        parser.add_argument('build_file', nargs = '?', default = 'build.py',
            help = 'name of the input file - default: build.py')
        parser.add_argument('-V', '--version', action = 'version', version = version_info)
        parser.add_argument('-M', '--makefile', action = 'store_true', help = 'enable makefile mode')
        parser.add_argument('-o', '--output', nargs = 1, default = None,
            help = 'name of output build file')
        args = parser.parse_args()
        if args.output:
            args.output = args.output[0]
        bfn = args.build_file
    except ImportError:
        optparse = __import__('optparse')
        parser = optparse.OptionParser(usage = 'pyrate [options] build_file')
        parser.add_option('-V', '--version', action='store_true', help = 'display version')
        parser.add_option('-M', '--makefile', action = 'store_true', help = 'enable makefile mode')
        parser.add_option('-o', '--output', default = None,
            help = 'name of output build file', dest='output')
        (args, posargs) = parser.parse_args()
        if len(posargs) > 1:
            sys.stderr.write('too many build_file arguments provided! %s\n' % repr(posargs))
            return os.EX_USAGE
        elif not posargs:
            posargs = ['build.py']
        bfn = posargs[0]
        if args.version:
            sys.stderr.write(version_info + '\n')
            sys.exit(os.EX_OK)

    generate_build_file(bfn, args.output, args.makefile)

################################################################################
# Externals + helper functions
################################################################################
项目:redisrwlock    作者:veshboo    | 项目源码 | 文件源码
def test_option_unrecognized(self):
        """test usage error for unrecognized option"""
        cmd, output = runCmdOutput(['--unrecognized'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
项目:redisrwlock    作者:veshboo    | 项目源码 | 文件源码
def test_option_unhandled(self):
        """test not handled option with hidden test option"""
        cmd, output = runCmdOutput(['--__unhandled__'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
项目:redisrwlock    作者:veshboo    | 项目源码 | 文件源码
def test_option_server_port(self):
        """test --server and --port options"""
        # empty redis-server host name
        cmd, output = runCmdOutput(['-s', '', '-p', '7788'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
        # port number out of range
        cmd, output = runCmdOutput(['-s', 'localhost', '-p', '99999'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
项目:pytypes    作者:Stewori    | 项目源码 | 文件源码
def err_no_in_file():
    print("Error: No in_file given! Use -h for help.")
    sys.exit(os.EX_USAGE)
项目:jipdate    作者:Linaro    | 项目源码 | 文件源码
def main(argv):
    parser = get_parser()

    # The parser arguments (cfg.args) are accessible everywhere after this call.
    cfg.args = parser.parse_args()

    # This initiates the global yml configuration instance so it will be
    # accessible everywhere after this call.
    cfg.initiate_config()

    if not cfg.args.file and not cfg.args.q:
        eprint("No file provided and not in query mode\n")
        parser.print_help()
        sys.exit(os.EX_USAGE)

    jira, username = jiralogin.get_jira_instance(cfg.args.t)

    if cfg.args.x or cfg.args.e:
        if not cfg.args.q:
            eprint("Arguments '-x' and '-e' can only be used together with '-q'")
            sys.exit(os.EX_USAGE)

    if cfg.args.p and not cfg.args.q:
        eprint("Arguments '-p' can only be used together with '-q'")
        sys.exit(os.EX_USAGE)

    if cfg.args.q:
        filename = get_jira_issues(jira, username)

        if cfg.args.p:
            print_status_file(filename)
            sys.exit(os.EX_OK)
    elif cfg.args.file is not None:
        filename = cfg.args.file
    else:
        eprint("Trying to run script with unsupported configuration. Try using --help.")
        sys.exit(os.EX_USAGE)

    if get_editor():
        open_editor(filename)
    parse_status_file(jira, filename)
项目:sshady    作者:droberson    | 项目源码 | 文件源码
def sigint_handler(signum, frame):
    """ sigint_handler() -- Generic SIGINT handler
    """
    xprint("[-] Caught SIGINT.")
    xprint("[-] Exiting..")
    exit(os.EX_USAGE)
项目:thefuzz    作者:droberson    | 项目源码 | 文件源码
def __init__(self, bindaddr="0.0.0.0", port=4444, backlog=5):
        self.inputs = []
        self.outputs = []
        self.clientmap = {}
        self.banner = None

        self.fuzz_queue = Queue.Queue()

        # Validate IP address
        try:
            socket.inet_aton(bindaddr)
        except socket.error:
            print "[-] Invalid bindaddr: %s" % bindaddr
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Validate port number
        if port > 65535 or port < 1:
            print "[-] Invalid port number: %d" % port
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Create listen socket
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.setblocking(0)

        # bind to port
        try:
            self.server.bind((bindaddr, port))
        except socket.error, exp:
            print "[-] Unable to bind to %s:%d: %s" % (bindaddr, port, exp)
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        print "[+] Listening on %s:%d" % (bindaddr, port)
        self.server.listen(backlog)

        signal.signal(signal.SIGINT, self.siginthandler)
项目:redisrwlock    作者:veshboo    | 项目源码 | 文件源码
def main():
    # Default values
    opt_repeat = False
    opt_interval = 5
    opt_server = "localhost"
    opt_port = 6379
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "hVri:s:p:",
            ["help", "version", "repeat", "interval=", "server=", "port=",
             "__unhandled__"])
    except getopt.GetoptError as err:
        print("ERROR:", err)
        sys.exit(os.EX_USAGE)
    for opt, opt_arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-V", "--version"):
            version()
            sys.exit()
        elif opt in ("-r", "--repeat"):
            opt_repeat = True
        elif opt in ("-i", "--interval"):
            try:
                opt_interval = int(opt_arg)
                if opt_interval == 0:
                    raise ValueError
            except:
                print("ERROR: specify interval as number of seconds")
                sys.exit(os.EX_USAGE)
        elif opt in ("-s", "--server"):
            opt_server = opt_arg
            if len(opt_server) == 0:
                print("ERROR: specify host name or address of redis-server")
                sys.exit(os.EX_USAGE)
        elif opt in ("-p", "--port"):
            try:
                opt_port = int(opt_arg)
                if not 0 <= opt_port <= 65535:
                    raise ValueError
            except:
                print("ERROR: specify port as number in [0, 65535]")
                sys.exit(os.EX_USAGE)
        else:
            print("ERROR: unhandled option")
            sys.exit(os.EX_USAGE)
    logging_config()
    logger = logging.getLogger(__name__)
    # Gc periodically
    client = RwlockClient(StrictRedis(host=opt_server, port=opt_port))
    while True:
        logger.info('redisrwlock gc')
        client.gc()
        if not opt_repeat:
            break
        time.sleep(opt_interval)
项目:sshady    作者:droberson    | 项目源码 | 文件源码
def main():
    """ main() -- entry point of program

    Args:
        None

    Returns:
        os.EX_OK on successful run
        os_EX_USAGE on failed run
    """
    signal.signal(signal.SIGINT, sigint_handler)

    args = parse_cli()

    if args.nocolor:
        Color.disable()

    # Need to configure terse first for proper output
    Settings.set("terse", args.terse)

    xprint("[+] sshady.py -- by Daniel Roberson @dmfroberson")
    xprint("")

    # Update setting for whether or not to attempt cracking of SSH keys
    Settings.set("crack", args.nocrack)

    # Make sure settings are sane
    if not Settings.update_wordlist(args.wordlist) or \
       not Settings.update_output_directory(args.outdir) or \
       not Settings.update_user_file(args.users) or \
       not Settings.update_host_file(args.hosts):
        return os.EX_USAGE

    # Search for users passwords.
    # TODO don't do this if key directory is specified.
    find_ssh_directories()

    # If a hostfile is specified, loop through hosts and try to login with
    # each of the harvested keys.
    if Settings.config("hostfile"):
        attempt_ssh_logins()

    xprint("")
    xprint("[+] You must defeat Sheng Long to stand a chance.")
    xprint("[+] Done.")

    return os.EX_OK