python argparse.argumentparser 什么都不输入 显示python2.7帮助文档chm

Python argparse.ArgumentParser Examples
Python argparse.ArgumentParser Examples
The following are 60
code examples for showing how to use
argparse.ArgumentParser. They are
extracted from open source Python projects.
You can click
vote up the examples you like, or click
to vote down the exmaples you don't like.
Your votes will be used in our system to extract more high-quality examples.
You may also check out all available functions/classes of the module
From project networking-brocade-master,
under directory tools,
in source file subunit-trace.py.
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--no-failure-debug', '-n', action='store_true',
dest='print_failures', help='Disable printing failure '
'debug information in realtime')
parser.add_argument('--fails', '-f', action='store_true',
dest='post_fails', help='Print failure debug '
'information after the stream is proccesed')
parser.add_argument('--failonly', action='store_true',
dest='failonly', help=&Don't print success items&,
os.environ.get('TRACE_FAILONLY', False)
is not False))
return parser.parse_args()
From project docker-image-updater-master,
under directory diu,
in source file main.py.
def _create_parser(self):
Create the argparse argument parser.
An instance of `argparse.ArgumentParser()`
parser = argparse.ArgumentParser()
parser.add_argument(
&-f&, &--file&,
default=&/etc/docker-image-updater.yml&,
help=&the config file to use&
parser.add_argument(
&--debug&,
action=&store_true&,
help=&show debug messages&
return parser
From project puppet-log_processor-master,
under directory files,
in source file log-gearman-worker.py.
def main():
parser = argparse.ArgumentParser()
parser.add_argument(&-c&, &--config&, required=True,
help=&Path to yaml config file.&)
parser.add_argument(&-d&, &--debuglog&,
help=&Enable debug log. &
&Specifies file to write log to.&)
parser.add_argument(&--foreground&, action='store_true',
help=&Run in the foreground.&)
parser.add_argument(&-p&, &--pidfile&,
default=&/var/run/jenkins-log-pusher/&
&jenkins-log-gearman-worker.pid&,
help=&PID file to lock during daemonization.&)
args = parser.parse_args()
with open(args.config, 'r') as config_stream:
config = yaml.load(config_stream)
server = Server(config, args.debuglog)
if args.foreground:
server.setup_logging()
server.main()
pidfile = pidfile_mod.TimeoutPIDLockFile(args.pidfile, 10)
with daemon.DaemonContext(pidfile=pidfile):
server.setup_logging()
server.main()
From project puppet-log_processor-master,
under directory files,
in source file log-gearman-client.py.
def main():
parser = argparse.ArgumentParser()
parser.add_argument(&-c&, &--config&, required=True,
help=&Path to yaml config file.&)
parser.add_argument(&-d&, &--debuglog&,
help=&Enable debug log. &
&Specifies file to write log to.&)
parser.add_argument(&--foreground&, action='store_true',
help=&Run in the foreground.&)
parser.add_argument(&-p&, &--pidfile&,
default=&/var/run/jenkins-log-pusher/&
&jenkins-log-gearman-client.pid&,
help=&PID file to lock during daemonization.&)
args = parser.parse_args()
with open(args.config, 'r') as config_stream:
config = yaml.load(config_stream)
server = Server(config, args.debuglog)
if args.foreground:
server.setup_logging()
server.main()
pidfile = pidfile_mod.TimeoutPIDLockFile(args.pidfile, 10)
with daemon.DaemonContext(pidfile=pidfile):
server.setup_logging()
server.main()
From project mockpy-master,
under directory mockpy/utils,
in source file args_parser.py.
def parse():
parser = argparse.ArgumentParser(
description='Start a mock server that reads input yaml res from inout directory.')
sub_parsers = parser.add_subparsers(title=&Commands&, dest=&sub&)
parser.add_argument('--version', help=&Display version&, action=&count&)
add_start_parser(sub_parsers)
add_init_parser(sub_parsers)
add_cleanup_parser(sub_parsers)
if has_pre_parse(parser):
return pre_parse()
parsed_args = parser.parse_args()
parsed_args.init = parsed_args.sub == &init&
parsed_args.cleanup = parsed_args.sub == &cleanup&
if (parsed_args.init or parsed_args.cleanup) is False:
validate_input(parsed_args)
return parsed_args
From project netcompare-master,
under directory ,
in source file netcompare.py.
def cli_parser():
parser = argparse.ArgumentParser(
description=('Generating configuration commands by finding differences'
' between two Cisco IOS style configuration files'))
parser.add_argument('origin', metavar='origin',
type=str, help='Origin configuration file')
parser.add_argument('target', metavar='target',
type=str, help='Target configuration file')
parser.add_argument('no_command', metavar='no_command',
type=str, help='Negation command keyword')
return parser.parse_args()
From project edgerouter-master,
under directory ,
in source file edgerouter.py.
def get_arg_parser():
parser = argparse.ArgumentParser(
description=&Marathon HAProxy Service Router&)
parser.add_argument(&--marathon&, &-m&,
required=True,
nargs=&+&,
help=&Marathon endpoint, eg. & +
&-m http://marathon1:8080 & +
&-m http://marathon2:8080&)
parser.add_argument(&--ssl-cert&,
help=&Enables HTTP virtual host proxying.& +
&Specifies the location of ssl cert to use for & +
&virtual host proxying&,
default=None)
parser.add_argument(&--disable-http&,
help=&Disable HTTP virtual host proxying&,
default=False,
action='store_true')
parser.add_argument(&--haproxy-config&,
help=&Location of haproxy configuration&,
default=&/etc/haproxy/haproxy.cfg&
parser.add_argument(&--group&,
help=&Only generate config for apps which list the &
&specified names. Defaults to apps without groups. &
&Use '*' to match all groups&,
action=&append&,
default=list())
return parser
From project blogofile,
under directory blogofile/tests,
in source file test_main.py.
def _parse_args(self, *args):
&&&Set up sub-command parser, parse args, and return result.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
main._setup_help_parser(subparsers)
return parser.parse_args(*args)
From project os-testr-master,
under directory os_testr,
in source file subunit_trace.py.
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--no-failure-debug', '-n', action='store_true',
dest='print_failures', help='Disable printing failure '
'debug information in realtime')
parser.add_argument('--fails', '-f', action='store_true',
dest='post_fails', help='Print failure debug '
'information after the stream is proccesed')
parser.add_argument('--failonly', action='store_true',
dest='failonly', help=&Don't print success items&,
os.environ.get('TRACE_FAILONLY', False)
is not False))
parser.add_argument('--abbreviate', '-a', action='store_true',
dest='abbreviate', help='Print one character status'
'for each test')
parser.add_argument('--perc-diff', '-d', action='store_true',
dest='enable_diff',
help=&Print percent change in run time on each test &)
parser.add_argument('--diff-threshold', '-t', dest='threshold',
help=&Threshold to use for displaying percent change &
&from the avg run time. If one is not specified &
&the percent change will always be displayed&)
parser.add_argument('--no-summary', action='store_true',
help=&Don't print the summary of the test run after &
& completes&)
return parser.parse_args()
Example 10
From project recordpeeker-master,
under directory recordpeeker/bin,
in source file command_line.py.
def parse_args(argv):
parser = argparse.ArgumentParser(&forever24&, description=&finds all the fabulous no.024s&)
parser.add_argument(&--find&, default=&024&, help=&specify what you're looking for&)
parser.add_argument(&--port&, &-p&, type=int, default=8080, help=&Specify the port recordpeeker runs on&)
parser.add_argument(&--verbosity&, &-v&, default=0, type=int, choices=[0,1,2,3], help=&Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.&)
return parser.parse_args(argv[1:])
Example 11
From project recordpeeker-master,
under directory recordpeeker,
in source file command_line.py.
def parse_args(argv):
parser = argparse.ArgumentParser(&Test&)
parser.add_argument(&--port&, &-p&, type=int, default=8080, help=&Specify the port recordpeeker runs on&)
parser.add_argument(&--verbosity&, &-v&, default=0, type=int, choices=[0,1,2,3], help=&Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.&)
return parser.parse_args(argv[1:])
Example 12
From project virt-deploy-master,
under directory virtdeploy,
in source file cli.py.
def parse_command_line(cmdline):
parser = argparse.ArgumentParser()
version = pkg_resources.get_distribution('virt-deploy').version
parser.add_argument('-v', '--version', action='version',
version='%(prog)s {0}'.format(version))
cmd = parser.add_subparsers(dest='command')
cmd_create = cmd.add_parser('create', help='create a new instance')
cmd_create.add_argument('id', help='new instance id')
cmd_create.add_argument('template', help='template id')
cmd_start = cmd.add_parser('start', help='start an instance')
cmd_start.add_argument('--wait', action='store_true',
help='wait for ssh access availability')
cmd_start.add_argument('name', help='name of instance to start')
cmd_stop = cmd.add_parser('stop', help='stop an instance')
cmd_stop.add_argument('name', help='name of instance to stop')
cmd_delete = cmd.add_parser('delete', help='delete an instance')
cmd_delete.add_argument('name', help='name of instance to delete')
cmd.add_parser('templates', help='list all the templates')
cmd_address = cmd.add_parser('address', help='instance ip address')
cmd_address.add_argument('name', help='instance name')
cmd_ssh = cmd.add_parser('ssh', help='connects to the instance')
cmd_ssh.add_argument('name', help='instance name')
cmd_ssh.add_argument('arguments', nargs='*', help='ssh arguments')
args = parser.parse_args(args=cmdline)
return COMMAND_mand](args)
Example 13
From project android-localization-helper-master,
under directory ,
in source file translation_helper.py.
def parseArgs(args=None):
# parse arguments and do error checking
parser = argparse.ArgumentParser()
parser.add_argument('--res',
help='Path to the app\'s res/ directory. If not '
'specifies it assumes current directory',
default='.')
parser.add_argument('--input',
nargs='+',
help='String files to include from default values '
'dir (e.g. strings.xml plurals.xml). By default, '
'only strings.xml is used')
parser.add_argument('--output',
help='Path to the output directory. If not specifies '
'it will create a folder called to_translate in the '
'current directory',
default='./to_translate')
parser.add_argument('--clean',
help='re-orders and removes strings in the '
'translation files to match the default string '
'ordering',
action=&store_true&)
args = parser.parse_args(args) if args is not None else parser.parse_args()
return args.res, args.clean, args.output, args.input
Example 14
From project deep-go-wrap-master,
under directory ,
in source file hdf2deepcl_v2.py.
def parse_args():
parser = argparse.ArgumentParser(
description='Converts the HDF5 dataset to the binary'
' format v2 compatible with DeepCL.'
' The v2 format specification is available at:'
' /hughperkins/kgsgo-dataset-preprocessor'
' The HDF5 dataset must be created using'
' these two options:'
' &-p clark_storkey_2014_packed -l simple_label&'
' or this will fail.')
parser.add_argument('filename_in', metavar='FILENAME_IN',
help='HDF5 filename to read the dataset to')
parser.add_argument('filename_out', metavar='FILENAME_OUT',
help='deepcl v2 filename to store result to')
parser.add_argument('--x-name',
dest='xname',
help='HDF5 dataset name to read the xs from',
default='xs')
parser.add_argument('--y-name', dest='yname',
help='HDF5 dataset name to read the ys from',
default='ys')
return parser.parse_args()
Example 15
From project Theano-Lights-master,
under directory scripts,
in source file text_tokenizer.py.
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('path', default=&ntst&)
parser.add_argument('--level', default='words')
parser.add_argument('--oov-rate', type=float, default=0.)
parser.add_argument('--dtype', default='int32')
return parser
Example 16
From project gtfsdb-master,
under directory gtfsdb,
in source file scripts.py.
def get_args():
''' database load command-line arg parser and help util...
tables = sorted([t.name for t in Base.metadata.sorted_tables])
parser = argparse.ArgumentParser(
prog='gtfsdb-load',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file', help='URL or local path to GTFS zip FILE')
parser.add_argument('--batch_size', '-b', default=config.DEFAULT_BATCH_SIZE,
help='BATCH SIZE to use for memory management')
parser.add_argument('--database_url', '-d', default=config.DEFAULT_DATABASE_URL,
help='DATABASE URL with appropriate privileges')
parser.add_argument('--is_geospatial', '-g', action='store_true',
default=config.DEFAULT_IS_GEOSPATIAL,
help='Database supports GEOSPATIAL functions')
parser.add_argument('--schema', '-s', default=config.DEFAULT_SCHEMA,
help='Database SCHEMA name')
parser.add_argument('--tables', choices=tables, default=None, nargs='*',
help='Limited list of TABLES to load, if blank, load all tables')
args = parser.parse_args()
kwargs = dict(
batch_size=args.batch_size,
schema=args.schema,
is_geospatial=args.is_geospatial,
tables=args.tables,
url=args.database_url,
return args, kwargs
Example 17
From project gummer-master,
under directory ,
in source file gummer.py.
def init():
logger = set_up_log()
parser = argparse.ArgumentParser()
parser.add_argument(&-l&, &--list_anal&, action='store_true',
help=&List analyzers.&)
parser.add_argument(&-ldb&, &--list_databases&, action='store_true',
help=&List db connectors.&)
parser.add_argument(&-lo&, &--list_outputs&, action='store_true',
help=&List possible output formats.&)
parser.add_argument(&-lc&, &--list_collectors&, action='store_true',
help=&List collectors.&)
parser.add_argument(&-a&, &--analyzer&, nargs=1,
help=&ID of the analyzer to use.&)
parser.add_argument(&-db&, &--dbconnector&, nargs=1,
help=&ID of the database connector to use.&)
parser.add_argument(&-o&, &--output&, nargs=1,
help=&ID of the output to use.&)
parser.add_argument(&-c&, &--collector&, nargs=1,
help=&ID of the collector to use.&)
return parser, logger
Example 18
From project docker-postgres-client-master,
under directory ,
in source file client.py.
def parser(self):
parser = argparse.ArgumentParser()
parser.add_argument(
'-c', '--container', help=&Container name&,
default=&containers_postgres_1&)
parser.add_argument(
'-p', '--port', help=&Container internal port&, default=5432)
parser.add_argument('-U', '--user', help=&Container user&,
default='postgres')
return parser
Example 19
From project gecko-dev,
under directory mobile/android/base,
in source file jni-generator.py.
def main():
parser = argparse.ArgumentParser(
description='Generate mozglue bindings for JNI functions.')
parser.add_argument('inputfile', type=argparse.FileType('r'))
parser.add_argument('outputfile', type=argparse.FileType('w'))
args = parser.parse_args()
gen = Generator(args.outputfile)
gen.process(args.inputfile)
args.outputfile.close()
args.inputfile.close()
Example 20
From project gecko-dev,
under directory python/mozbuild/mozbuild/action,
in source file xpidl-process.py.
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--cache-dir',
help='Directory in which to find or write cached lexer data.')
parser.add_argument('inputdir',
help='Directory in which to find source .idl files.')
parser.add_argument('headerdir',
help='Directory in which to write header files.')
parser.add_argument('xptdir',
help='Directory in which to write xpt file.')
parser.add_argument('depsdir',
help='Directory in which to write dependency files.')
parser.add_argument('module',
help='Final module name to use for linked output xpt file.')
parser.add_argument('idls', nargs='+',
help='Source .idl file(s). Specified as stems only.')
parser.add_argument('-I', dest='incpath', action='append', default=[],
help='Extra directories where to look for included .idl files.')
args = parser.parse_args(argv)
process(args.inputdir, args.incpath, args.cache_dir, args.headerdir,
args.xptdir, args.depsdir, args.module, args.idls)
Example 21
From project gecko-dev,
under directory python/mozbuild/mozbuild/action,
in source file process_install_manifest.py.
def main(argv):
parser = argparse.ArgumentParser(
description='Process install manifest files.')
parser.add_argument('destdir', help='Destination directory.')
parser.add_argument('manifests', nargs='+', help='Path to manifest file(s).')
parser.add_argument('--no-remove', action='store_true',
help='Do not remove unaccounted files from destination.')
parser.add_argument('--no-remove-all-directory-symlinks', action='store_true',
help='Do not remove all directory symlinks from destination.')
parser.add_argument('--no-remove-empty-directories', action='store_true',
help='Do not remove empty directories from destination.')
args = parser.parse_args(argv)
result = process_manifest(args.destdir, args.manifests,
remove_unaccounted=not args.no_remove,
remove_all_directory_symlinks=not args.no_remove_all_directory_symlinks,
remove_empty_directories=not args.no_remove_empty_directories)
print(COMPLETE.format(dest=args.destdir,
existing=result.existing_files_count,
updated=result.updated_files_count,
rm_files=result.removed_files_count,
rm_dirs=result.removed_directories_count))
Example 22
From project Scripts-master,
under directory ,
in source file unpack_apk.py.
def main():
parser = argparse.ArgumentParser(
description='Script to unpack APKs and concatenate in the same file.')
parser.add_argument('input', action='store', help='APK to unpack')
parser.add_argument('-o', '--output', dest='output',
help='output file, by default is &input + .unpacked&',
default=None)
args = parser.parse_args()
if not args.output:
args.output = args.input + &.unpacked&
unpack(args.input, args.output)
Example 23
From project Scripts-master,
under directory ,
in source file download_androguard_report.py.
def main():
parser = argparse.ArgumentParser(
description='Tool to download reports from Koodous')
parser.add_argument('-s', '--sha256', action='store',
dest='sha256')
parser.add_argument('-o', '--output', action='store', dest='filename',
help='File to dump the downloaded report, by default: {sha256}-report.json')
args = parser.parse_args()
if len(TOKEN) == 0:
print 'You must provide you token access in the script (register in Koodous, it\'s free!'
if not args.sha256:
print &I need at least a SHA256 hash!&
parser.print_help()
report_name = '%s-report.json' % args.sha256
if args.filename:
report_name = args.filename
success = download_report(sha256=args.sha256, dst=report_name, token=TOKEN)
if success:
print 'Androguard report saved in %s' % report_name
Example 24
From project Scripts-master,
under directory ,
in source file compare_apks.py.
def main():
parser = argparse.ArgumentParser(
description='Script to compare permissions of 2 APKs based on Koodous.')
parser.add_argument('hash1', action='store', help='sha256 of first APK')
parser.add_argument('hash2', action='store', help='sha256 of seconds APK')
parser.add_argument('token', action='store', help='Koodous token API')
parser.add_argument('--ssdeep', dest='ssdeep', action='store_true',
help=&Calculate several comparisons between APKs based on ssdeep hash&)
args = parser.parse_args()
report1 = download_report(args.hash1, args.token)
report2 = download_report(args.hash2, args.token)
compare_permissions(report1, report2)
if args.ssdeep:
if IMPORT_SSDEEP:
compare_ssdeep(report1, report2)
print &You must to install ssdeep for python (https://pypi.python.org/pypi/ssdeep)&
print RED + error_msg + ENDC
Example 25
From project Scripts-master,
under directory ,
in source file scan_device.py.
def main():
Main function (check parameters and launch process)
parser = argparse.ArgumentParser(
description='Script to examine your mobile phone against Koodous database.')
parser.add_argument('token', action='store', help='Koodous token API')
args = parser.parse_args()
if check_device():
apks = get_apps()
print &Total APKs to check %d& % len(apks)
if apks == False:
print &Device connection problem, retry&
for apk in apks:
print &Extracting %s& % apk[1]
extract_apk(apk[0])
sha256 = hash256('sample.apk')
detected = check_detected(sha256, args.token)
if detected == True:
print &Detected %s& % apk[1]
elif detected == None:
print &Not in Koodous, uploading [%s] %s& % (apk[1], sha256)
upload(sha256, 'sample.apk', args.token)
elif detected == False:
print &%s is OK& % apk[1]
#Remove the last sample
os.remove('sample.apk')
print &No device connected&
Example 26
From project undocker-master,
under directory ,
in source file undocker.py.
def parse_args():
p = argparse.ArgumentParser()
p.add_argument('--ignore-errors', '-i',
action='store_true',
help='Ignore OS errors when extracting files')
p.add_argument('--output', '-o',
default='.',
help='Output directory (defaults to &.&)')
p.add_argument('--verbose', '-v',
action='store_const',
dest='loglevel')
p.add_argument('--debug', '-d',
action='store_const',
const=logging.DEBUG,
dest='loglevel')
p.add_argument('--layers',
action='store_true',
help='List layers in an image')
p.add_argument('--list', '--ls',
action='store_true',
help='List images/tags contained in archive')
p.add_argument('--layer', '-l',
action='append',
help='Extract only the specified layer')
p.add_argument('--no-whiteouts', '-W',
action='store_true',
help='Do not process whiteout (.wh.*) files')
p.add_argument('image', nargs='?')
p.set_defaults(level=logging.WARN)
return p.parse_args()
Example 27
From project portstat-master,
under directory portstat,
in source file portstat.py.
def main():
parser = argparse.ArgumentParser(
description='A simple port traffic monitor')
parser.add_argument('-c', '--config', type=str,
default='/etc/portstat.conf',
help='Path of the config file.')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-v', '--version', help='Show portstat version.', action='store_true')
group.add_argument(
'-s', '--sync',
help='Sync the portstat settings and iptables.', action='store_true')
group.add_argument(
'-u', '--upload',
help='Upload the port stat with webhook.', action='store_true')
args = parser.parse_args()
portGroups = getConfig(args.config)
if args.version:
print('portstat in version %s' % version())
if args.sync:
sync(portGroups)
if args.upload:
upload(portGroups)
Example 28
From project git-grid-master,
under directory gitgrid/utils,
in source file utils.py.
def controller_args(parser=None, parse=True):
if parser is None:
parser = argparse.ArgumentParser()
parser.add_argument(
'--controller', '-c',
default=&launchpad&,
parser.add_argument(
'--input', '-i',
default=None,
parser.add_argument(
'--output', '-o',
default=None,
return parser.parse_args()
return parser
Example 29
From project git-grid-master,
under directory pushcat,
in source file __init__.py.
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument(
'--daemonize', '-d', action=&store_true&,
parser.add_argument(
'--buflen', '-b', type=int, default=80,
args = parser.parse_args()
PushCat(args.daemonize, args.buflen)
Example 30
From project PyMVPA,
under directory mvpa2/support/afni,
in source file suma_setup_instacorr.py.
def _get_options():
yesno = [&yes&, &no&]
parser = argparse.ArgumentParser('Pre-processing for group-based connectivity/similarity analysis using AFNI and SUMA\nNikolaas N. Oosterhof Jan 2012')
parser.add_argument(&-i&, &--input&, required=False, nargs='*')
parser.add_argument(&more_input&, nargs='*')
parser.add_argument('-I', &--pad_to_ico_ld&, required=False, default=None)
parser.add_argument('-N', &--pad_to_node&, required=False, default=None)
parser.add_argument('-p', '--prefix', default='z_full_')
parser.add_argument('-g', '--group_prefix', default='ALL_')
parser.add_argument('-G', '--group_postfix', default=None)
parser.add_argument(&-o&, &--overwrite&, required=False, action='store_true', help=&Overwrite existing files&)
namespace = parser.parse_args(None)
return vars(namespace)
Example 31
From project ShodanAPI-master,
under directory ,
in source file ShodanAPI.py.
def cli_parser():
# Command line argument parser
parser = argparse.ArgumentParser(
add_help=False,
description=&\033[0;37mShodan API - Search Assistant Searching shodan via API.\033[92m \n By : Alexcerus&)
parser.add_argument(
&-search&, metavar=&Apache server&, default=False,
help=&when searching Shodan for a string.&)
parser.add_argument(
&-f&, metavar=&ips.txt&, default=None,
help=&Using THe Ips List - File containing IPs to search shodan for.&)
parser.add_argument(
&-ip&, metavar='217.140.75.46', default=False,
help=&Shodan Host Search against IP & return results from Shodan about a specific IP.&)
parser.add_argument(
&-iprg&, metavar='217.140.75.46/24', default=False,
help=&Used to return results from Shodan about a specific CIDR to IP range .&)
parser.add_argument(
&--hostnameonly&, action='store_true',
help=&[Optional] Only provide results with a Shodan stored hostname.&)
parser.add_argument(
&--page&, metavar='1', default=1,
help=&Page number of results to return (default 1 (first page)).&)
parser.add_argument(
'-H','-h', '-?', '--h', '-help', '--help', action=&store_true&,
help=argparse.SUPPRESS)
args = parser.parse_args()
if args.h:
parser.print_help()
sys.exit()
return args.search, args.ip, args.iprg, args.hostnameonly, args.page, args.f
Example 32
From project terraform.py-master,
under directory ,
in source file terraform.py.
def main():
parser = argparse.ArgumentParser(
__file__, __doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
modes = parser.add_mutually_exclusive_group(required=True)
modes.add_argument('--list',
action='store_true',
help='list all variables')
modes.add_argument('--host', help='list variables for a single host')
modes.add_argument('--version',
action='store_true',
help='print version and exit')
modes.add_argument('--hostfile',
action='store_true',
help='print hosts as a /etc/hosts snippet')
parser.add_argument('--pretty',
action='store_true',
help='pretty-print output JSON')
parser.add_argument('--nometa',
action='store_true',
help='with --list, exclude hostvars')
default_root = os.environ.get('TERRAFORM_STATE_ROOT',
os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', )))
parser.add_argument('--root',
default=default_root,
help='custom root to search for `.tfstate`s in')
args = parser.parse_args()
if args.version:
print('%s %s' % (__file__, VERSION))
parser.exit()
hosts = iterhosts(iterresources(tfstates(args.root)))
if args.list:
output = query_list(hosts)
if args.nometa:
del output['_meta']
print(json.dumps(output, indent=4 if args.pretty else None))
elif args.host:
output = query_host(hosts, args.host)
print(json.dumps(output, indent=4 if args.pretty else None))
elif args.hostfile:
output = query_hostfile(hosts)
print(output)
parser.exit()
Example 33
From project os-testr-master,
under directory os_testr,
in source file os_testr.py.
def get_parser():
parser = argparse.ArgumentParser(
description='Tool to run openstack tests')
parser.add_argument('--blacklist_file', '-b',
help='Path to a blacklist file, this file contains a'
' separate regex exclude on each newline')
group = parser.add_mutually_exclusive_group()
group.add_argument('--regex', '-r',
help='A normal testr selection regex. If a blacklist '
'file is specified, the regex will be appended '
'to the end of the generated regex from that '
group.add_argument('--path', metavar='FILE_OR_DIRECTORY',
help='A file name or directory of tests to run.')
group.add_argument('--no-discover', '-n', metavar='TEST_ID',
help=&Takes in a single test to bypasses test &
&discover and just excute the test specified. &
&A file name may be used in place of a test &
pretty = parser.add_mutually_exclusive_group()
pretty.add_argument('--pretty', '-p', dest='pretty', action='store_true',
help='Print pretty output from subunit-trace. This is '
'mutually exclusive with --subunit')
pretty.add_argument('--no-pretty', dest='pretty', action='store_false',
help='Disable the pretty output with subunit-trace')
parser.add_argument('--subunit', '-s', action='store_true',
help='output the raw subunit v2 from the test run '
'this is mutually exclusive with --pretty')
parser.add_argument('--list', '-l', action='store_true',
help='List all the tests which will be run.')
slowest = parser.add_mutually_exclusive_group()
slowest.add_argument('--slowest', dest='slowest', action='store_true',
help=&after the test run print the slowest tests&)
slowest.add_argument('--no-slowest', dest='slowest', action='store_false',
help=&after the test run don't print the slowest &
parser.add_argument('--pdb', metavar='TEST_ID',
help='Run a single test that has pdb traces added')
parallel = parser.add_mutually_exclusive_group()
parallel.add_argument('--parallel', dest='parallel', action='store_true',
help='Run tests in parallel (this is the default)')
parallel.add_argument('--serial', dest='parallel', action='store_false',
help='Run tests serially')
parser.add_argument('--concurrency', '-c', type=int, metavar='WORKERS',
help='The number of workers to use when running in '
'parallel. By default this is the number of cpus')
parser.add_argument('--until-failure', action='store_true',
help='Run the tests in a loop until a failure is '
'encountered. Running with subunit or pretty'
'output enable will force the loop to run tests'
'serially')
parser.add_argument('--print-exclude', action='store_true',
help='If an exclude file is used this option will '
'prints the comment from the same line and all '
'skipped tests before the test run')
parser.set_defaults(pretty=True, slowest=True, parallel=True)
return parser
Example 34
From project diceware-master,
under directory diceware,
in source file __init__.py.
def handle_options(args):
&&&Handle commandline options.
random_sources = get_random_sources().keys()
wordlist_names = get_wordlist_names()
parser = argparse.ArgumentParser(
description=&Create a passphrase&,
epilog=&Wordlists are stored in %s& % WORDLISTS_DIR
parser.add_argument(
'-n', '--num', default=6, type=int,
help='number of words to concatenate. Default: 6')
cap_group = parser.add_mutually_exclusive_group()
cap_group.add_argument(
'-c', '--caps', action='store_true',
help='Capitalize words. This is the default.')
cap_group.add_argument(
'--no-caps', action='store_false', dest='capitalize',
help='Turn off capitalization.')
parser.add_argument(
'-s', '--specials', default=0, type=int, metavar='NUM',
help=&Insert NUM special chars into generated word.&)
parser.add_argument(
'-d', '--delimiter', default='',
help=&Separate words by DELIMITER. Empty string by default.&)
parser.add_argument(
'-r', '--randomsource', default='system', choices=random_sources,
metavar=&SOURCE&,
&Get randomness from this source. Possible values: `%s'. &
&Default: system& % &', `&.join(sorted(random_sources))))
parser.add_argument(
'-w', '--wordlist', default='en_8k', choices=wordlist_names,
metavar=&NAME&,
&Use words from this wordlist. Possible values: `%s'. &
&Wordlists are stored in the folder displayed below. &
&Default: en_8k& % &', `&.join(wordlist_names)))
parser.add_argument(
'infile', nargs='?', metavar='INFILE', default=None,
type=argparse.FileType('r'),
help=&Input wordlist. `-' will read from stdin.&,
parser.add_argument(
'--version', action='store_true',
help='output version information and exit.',
parser.set_defaults(capitalize=True)
args = parser.parse_args(args)
return args
Example 35
From project platespinning-master,
under directory countries,
in source file flags2_common.py.
def process_args(default_concur_req):
server_options = ', '.join(sorted(SERVERS))
parser = argparse.ArgumentParser(
description='Download flags for country codes. '
'Default: top 20 countries by population.')
parser.add_argument('cc', metavar='CC', nargs='*',
help='country code or 1st letter (eg. B for BA...BZ)')
parser.add_argument('-a', '--all', action='store_true',
help='get all available flags (AD to ZW)')
parser.add_argument('-e', '--every', action='store_true',
help='get flags for every possible code (AA...ZZ)')
parser.add_argument('-l', '--limit', metavar='N', type=int,
help='limit to N first codes', default=sys.maxsize)
parser.add_argument('-m', '--max_req', metavar='CONCURRENT', type=int,
default=default_concur_req,
help='maximum concurrent requests (default={})'
.format(default_concur_req))
parser.add_argument('-s', '--server', metavar='LABEL',
default=DEFAULT_SERVER,
help='S one of {} (default={})'
.format(server_options, DEFAULT_SERVER))
parser.add_argument('-v', '--verbose', action='store_true',
help='output detailed progress info')
args = parser.parse_args()
if args.max_req & 1:
print('*** Usage error: --max_req CONCURRENT must be &= 1')
parser.print_usage()
sys.exit(1)
if args.limit & 1:
print('*** Usage error: --limit N must be &= 1')
parser.print_usage()
sys.exit(1)
args.server = args.server.upper()
if args.server not in SERVERS:
print('*** Usage error: --server LABEL must be one of',
server_options)
parser.print_usage()
sys.exit(1)
cc_list = expand_cc_args(args.every, args.all, args.cc, args.limit)
except ValueError as exc:
print(exc.args[0])
parser.print_usage()
sys.exit(1)
if not cc_list:
cc_list = sorted(POP20_CC)
return args, cc_list
Example 36
From project s3-site-cache-optimizer-master,
under directory src/s3_site_cache_optimizer,
in source file optimize.py.
def main():
Main function for the s3-site-cache-optimizer CLI.
# init logger
global logger
logger = logging.getLogger('s3-site-cache-optimizer')
ch = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
# parse arguments
parser = argparse.ArgumentParser(
prog='s3-site-cache-optimizer',
description='Optimize a static website for hosting in S3, by including a fingerprint \
into all assets\' filenames. The optimized website is uploaded into the specified S3 \
bucket with the right cache headers.')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
parser.add_argument('--version', action='version', version='%(prog)s ' +
str(require(&s3-site-cache-optimizer&)[0].version))
parser.add_argument(&source_dir&, help='Local directory containing a static website.')
parser.add_argument(&destination_bucket&, help='S3 bucket name.')
parser.add_argument('--exclude', nargs='+', metavar=&PATTERN&, default=[],
help='Exclude files and directories matching these patterns.')
parser.add_argument('-o', '--output', dest='output_dir', default=None,
help='Output directory in which local files are written. When absent a \
temporary directory is created and used.')
parser.add_argument('--access-key', dest=&aws_access_key_id&, default=None,
help='AWS access key. If this field is not specified, credentials from \
environment or credentials files will be used.')
parser.add_argument('--secret-key', dest=&aws_secret_access_key&, default=None,
help='AWS access secret. If this field is not specified, credentials from \
environment or credentials files will be used.')
parser.add_argument('--region', default=None, help='AWS region to connect to.')
parser.add_argument('--gzip', action='store_true', help='Gzip text-based files.', default=False)
parser.add_argument('--prefix', default=None, help='Subdirectory in which files are stored in \
the bucket. Stored in the root of the \
bucket by default.')
parser.add_argument('--domains', nargs='+', metavar=&DOMAIN&, default=[],
help='Domain names on which the site will be hosted.')
parser.add_argument('--skip-s3-upload', dest=&skip_s3_upload&,
action='store_true', help='Skip uploading to S3.')
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
logger.error(e)
# set logging level
if args.debug:
logger.setLevel(logging.DEBUG)
Optimizer(args.source_dir, args.destination_bucket, exclude=args.exclude,
output_dir=args.output_dir, aws_access_key_id=args.aws_access_key_id,
aws_secret_access_key=args.aws_secret_access_key,
skip_s3_upload=args.skip_s3_upload, region=args.region,
domains=args.domains, prefix=args.prefix, gzip=args.gzip).run()
except Exception as e:
logger.critical(e)
Example 37
From project bareos-vmware-master,
under directory vmware_cbt_tool,
in source file vmware_cbt_tool.py.
def GetArgs():
Supports the command-line arguments listed below.
parser = argparse.ArgumentParser(
description='Process args for enabling/disabling/resetting CBT')
parser.add_argument('-s', '--host',
required=True,
action='store',
help='Remote host to connect to')
parser.add_argument('-o', '--port',
default=443,
action='store',
help='Port to connect on')
parser.add_argument('-u', '--user',
required=True,
action='store',
help='User name to use when connecting to host')
parser.add_argument('-p', '--password',
required=False,
action='store',
help='Password to use when connecting to host')
parser.add_argument('-d', '--datacenter',
required=True,
action='store',
help='DataCenter Name')
parser.add_argument('-f', '--folder',
required=True,
action='store',
help='Folder Name (must start with /, use / for root folder')
parser.add_argument('-v', '--vmname',
required=True,
action='append',
help='Names of the Virtual Machines')
parser.add_argument('--enablecbt',
action='store_true',
default=False,
help='Enable CBT')
parser.add_argument('--disablecbt',
action='store_true',
default=False,
help='Disable CBT')
parser.add_argument('--resetcbt',
action='store_true',
default=False,
help='Reset CBT (disable, then enable)')
parser.add_argument('--info',
action='store_true',
default=False,
help='Show information (CBT supported and enabled or disabled)')
args = parser.parse_args()
return args
Example 38
From project deep-go-wrap-master,
under directory ,
in source file process_sgf.py.
def parse_args():
parser = argparse.ArgumentParser(
description='Processes sgf to create datasets for teaching Deep'
' Neural Networks to play the game of Go.'
' Each sgf file is read from STDIN, analysed and an'
' (X, y) pair is created from each position, where'
' X is the cube encoding position and y the desired move.'
' The results are written to HDF5 file.')
parser.add_argument('filename', metavar='FILENAME',
help='HDF5 FILENAME to store the dataset to')
parser.add_argument('--x-name',
dest='xname',
help='HDF5 dataset name to store the xs to',
default='xs')
parser.add_argument('--y-name', dest='yname',
help='HDF5 dataset name to store the ys to',
default='ys')
parser.add_argument('-p', '--plane', type=str, choices=cubes.reg_cube.keys(),
default='clark_storkey_2014',
help='specify which method should be used to create the planes')
parser.add_argument('-l', '--label', type=str, choices=cubes.reg_label.keys(),
default='simple_label',
help='specify which method should be used to create the labels')
parser.add_argument('-q', '--quiet', dest='quiet', action='store_true',
default=False,
help='turn off the (stderr) debug logs')
parser.add_argument('-s', dest='boardsize', type=int,
help='specify boardsize', default=19)
parser.add_argument('--flatten', dest='flatten', action='store_true',
help='Flatten out the examples. (19, 19, 4) shape becomes ( 19 * 19 * 4,)', default=False)
parser.add_argument('--shrink-units', dest='shrink_units', action='store_true',
help='Shrinks unit dimension label (or, unlikely, feature) arrays.'
' Only if the unit dimension is the only one in the example,'
' so (19,19,1) is not shrinked, but (1,) is.', default=False)
parser.add_argument('--dtype', dest='dtype',
help='convert dtype of stored data to given numpy dtype (instead the default value defined by plane/label)', default=None)
parser.add_argument('--proc', type=int,
default=multiprocessing.cpu_count(),
help='specify number of processes for parallelization')
return parser.parse_args()
Example 39
From project txtnets-master,
under directory code/analysis,
in source file initial_script.py.
def run():
parser = argparse.ArgumentParser(
description=&Collect cluster data.&)
parser.add_argument(&--progress_dir&, help=&where the results subset of folders is&)
args = parser.parse_args()
#Preparing filenames
progress_dir = args.progress_dir
list_of_dictionaries = []
for result_folder in os.listdir(progress_dir):
if result_folder == '.DS_Store':
#LOADING DICTIONARIES
with open(os.path.join(progress_dir, result_folder, 'progress.pkl')) as file:
progress_dict = pickle.load(file)
except IOError:
print &Failed to load progress.pkl from {}&.format(result_folder)
with open(os.path.join(progress_dir, result_folder, 'params_train.yaml'), &r&) as stream:
params_train_dict = yaml.load(stream)
except IOError:
print &Failed to load params_train.yaml from {}&.format(result_folder)
with open(os.path.join(progress_dir, result_folder, 'params_experiment_config.yaml'), &r&) as stream:
params_experiment_dict = yaml.load(stream)
except IOError:
print &Failed to load params_experiment_config.yaml from {}&.format(result_folder)
#FLATTENING DICTIONARY
new_dictionary = dict()
for key in params_experiment_dict:
if key == 'word_layers':
for inner_dict in params_experiment_dict[key]:
for key in inner_dict:
new_dictionary[key+'_w_'+str(count)]=inner_dict[key]
count += 1
elif key == 'sentence_layers':
for inner_dict in params_experiment_dict[key]:
for key in inner_dict:
new_dictionary[key+'_s_'+str(count)]=inner_dict[key]
count += 1
new_dictionary[key]=params_experiment_dict[key]
params_experiment_dict = new_dictionary
#PUTTING DICTIONARIES TOGATHER
for batch_dict in progress_dict:
temp_dict = dict()
temp_dict.update(batch_dict)
temp_dict.update(params_experiment_dict)
temp_dict.update(params_train_dict)
list_of_dictionaries.append(temp_dict)
#GETTING IT INTO PANDA
data = pd.DataFrame(list_of_dictionaries)
with open(&pandas_data.pkl&, 'w') as file:
pickle.dump(data, file, protocol=-1)
Example 40
From project txtnets-master,
under directory code,
in source file visualise_trained_model.py.
def run():
parser = argparse.ArgumentParser(
description=&Evaluate a trained network on the sentiment140 test set&)
parser.add_argument(&--model_file&, help=&pickle file to load the model from&)
parser.add_argument(&--output_file&, help=&html file to write the output to&)
parser.add_argument(&--dataset&, help=&name of the dataset to visualise&)
args = parser.parse_args()
#Preparing filenames
model_file = os.path.join(model_dir, args.model_file)
test_file = os.path.join(data_dir, args.dataset, args.dataset + '.test.clean.json')
vocab_file = os.path.join(data_dir, args.dataset, args.dataset + '.train.clean.dictionary.encoding.json')
output_file = os.path.join(visual_dir, args.output_file)
#Opening model file
with open(model_file) as model_file:
model = pickle.load(model_file)
print model
#Opening data file to visualise
with open(test_file) as data_file:
data = json.loads(data_file.read())
X, Y = map(list, zip(*data))
Y_original = Y
Y = [[&:)&, &:(&].index(y) for y in Y]
#Loading vocabulary
with open(vocab_file) as alphabet_file:
alphabet = json.loads(alphabet_file.read())
#Tokenizing the data
tokenizer = WordPunctTokenizer()
new_X = []
for x in X:
new_X.append([w if w in alphabet else 'UNKNOWN' for w in tokenizer.tokenize(x)])
Y_hat, Y_inverted, delta = get_model_output(model, X, Y)
#print_visualisation(X, Y_hat, Y_inverted, delta, output_file)
extract_lexicon(X, Y_hat, Y_inverted, delta)
Example 41
From project pic2map-master,
under directory pic2map,
in source file cli.py.
def parse_arguments(argv):
&&&Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
parser = argparse.ArgumentParser(
description='Display pictures location in a map')
log_levels = ['debug', 'info', 'warning', 'error', 'critical']
parser.add_argument(
'-l', '--log-level',
dest='log_level',
choices=log_levels,
default='info',
help=('Log level. One of {0} or {1} '
'(%(default)s by default)'
.format(', '.join(log_levels[:-1]), log_levels[-1])))
subparsers = parser.add_subparsers(help='Subcommands')
add_parser = subparsers.add_parser('add', help=add.__doc__)
add_parser.add_argument(
'directory', type=valid_directory, help='Base directory')
add_parser.set_defaults(func=add)
remove_parser = subparsers.add_parser('remove', help=remove.__doc__)
remove_parser.add_argument(
'directory', type=valid_directory, help='Base directory')
remove_parser.set_defaults(func=remove)
count_parser = subparsers.add_parser('count', help=count.__doc__)
count_parser.set_defaults(func=count)
serve_parser = subparsers.add_parser('serve', help=serve.__doc__)
serve_parser.set_defaults(func=serve)
args = parser.parse_args(argv)
args.log_level = getattr(logging, args.log_level.upper())
return args
Example 42
From project homebrew-pypi-poet-master,
under directory poet,
in source file poet.py.
def main():
parser = argparse.ArgumentParser(
description='Generate Homebrew resource stanzas for pypi packages '
'and their dependencies.')
actions = parser.add_mutually_exclusive_group()
actions.add_argument(
'--single', '-s', metavar='package', nargs='+',
help='Generate a resource stanza for one or more packages, '
'without considering dependencies.')
actions.add_argument(
'--formula', '-f', metavar='package',
help='Generate a complete formula for a pypi package with its '
'recursive pypi dependencies as resources.')
actions.add_argument(
'--resources', '-r', metavar='package',
help='Generate resource stanzas for a package and its recursive '
'dependencies (default).')
parser.add_argument('package', help=argparse.SUPPRESS, nargs='?')
parser.add_argument('-V', '--version', action='version',
version='homebrew-pypi-poet {}'.format(__version__))
args = parser.parse_args()
if (args.formula or args.resources) and args.package:
print('--formula and --resources take a single argument.',
file=sys.stderr)
parser.print_usage(sys.stderr)
if args.formula:
print(formula_for(args.formula))
elif args.single:
for i, package in enumerate(args.single):
data = research_package(package)
print(RESOURCE_TEMPLATE.render(resource=data))
if i != len(args.single)-1:
package = args.resources or args.package
if not package:
parser.print_usage(sys.stderr)
print(resources_for(package))
Example 43
From project gecko-dev,
under directory xulrunner/app,
in source file install_app.py.
def handleCommandLine():
import argparse
# Argument parsing.
parser = argparse.ArgumentParser(
description=&XULRunner application installer&,
usage=&&&install_app.py appLocation installDir greDir [--appName APPNAME]
install_app.py -h
install_app.py --version
parser.add_argument(
&appLocation&,
action=&store&,
help=&The directory or ZIP file containing application.ini as a top-level child file&
parser.add_argument(
&installDir&,
action=&store&,
help=&The directory to install the application to&
parser.add_argument(
&--greDir&,
action=&store&,
help=&The directory containing the Gecko SDK (usually where this Python script lives)&,
default=os.path.dirname(sys.argv[0])
parser.add_argument(
&--appName&,
action=&store&,
help=&The name of the application to install&
parser.add_argument(&--version&, action=&version&, version=&%(prog)s 1.0&)
# The command code.
cmds = parser.parse_args()
installApp(cmds.appLocation, cmds.installDir, cmds.appName, cmds.greDir)
except exn:
shutil.rmtree(cmds.installDir)
print cmds.appName + & application installed to & + cmds.installDir
Example 44
From project processing.py,
under directory examples.py/Python/colornames/namethatcolor,
in source file NameThatColor.py.
def main():
import json
import argparse
output_choices = {
'match_hex': lambda m: m.hex_value,
'match_name': lambda m: m.name,
'is_exact': lambda m: m.exact,
'original_hex': lambda m: m.original
format_choices = {
'json': lambda r: json.dumps(r),
'raw' : lambda r: r
parser = argparse.ArgumentParser(
description=&Find the closest known color name for a hex value&)
parser.add_argument('-c', '--colors', dest='colors_file',
help=&a csv file of known color name definitions&)
parser.add_argument('target',
help=&hex value of the color to search for&)
parser.add_argument('-o', '--output',
dest=&output&,
nargs='*',
choices=output_choices.keys(),
default=['match_hex', 'match_name'],
help=&what information about the color match to output&)
parser.add_argument('--format',
dest=&format&,
choices=format_choices.keys(),
default=&json&,
help=&what format to return data in&)
args = parser.parse_args()
Namer = NameThatColor(args.colors_file)
match = Namer.name(args.target)
result = {}
for choice in args.output:
result[choice] = output_choices[choice](match)
print format_choices[args.format](result)
Example 45
From project cmssw,
under directory PhysicsTools/PythonAnalysis/python/rootplot,
in source file rootmath.py.
def main():
parser = argparse.ArgumentParser()
parser.add_argument('filenames', type=str, nargs='+',
help='root files to process')
parser.add_argument('--dirs', type=str, nargs='+', default=['/'],
help='target directori paths to '
'histograms will be relative to these')
parser.add_argument('--add', default=[], action='append', nargs='*',
help='a list of directories or histograms to add')
parser.add_argument('--subtract', default=[], action='append', nargs='*',
help='a list of directories or histograms to subtract')
parser.add_argument('--divide', default=[], action='append', nargs='*',
help='2 directories or histograms to divide')
parser.add_argument('--bayes-divide', default=[], action='append', nargs='*',
help='2 directories or histograms from which to make '
'an efficiency plot')
args = parser.parse_args()
separators = {'add' : '_plus_',
'subtract' : '_minus_',
'divide' : '_div_',
'bayes_divide' : '_eff_'}
files = [ROOT.TFile(x, 'read') for x in args.filenames]
outfile = ROOT.TFile('out.root', 'recreate')
for d in args.dirs:
dirs += rootglob(files[0], d)
if len(files) == 1:
f = files[0]
for thisdir in dirs:
for operation_type, separator in separators.items():
for arg_set in getattr(args, operation_type):
paths = [joined(thisdir, x) for x in arg_set]
if f.GetDirectory(paths[0]):
destdir = pathdiff(paths, separator)
for target in [os.path.basename(x) for x in
rootglob(f, paths[0] + '/*')]:
hists = [f.GetDirectory(x).Get(target)
for x in paths]
if not alltrue([x and x.InheritsFrom('TH1')
for x in hists]):
dest = joined(destdir, target)
math_func = globals()[operation_type]
math_func(outfile, dest, hists)
hists = [f.GetDirectory(thisdir).Get(x) for x in paths]
if not alltrue([x and x.InheritsFrom('TH1')
for x in hists]):
dest = pathdiff(paths, separator)
math_func = globals()[operation_type]
math_func(outfile, dest, hists)
for operation_type, separator in separators.items():
arg_sets = getattr(args, operation_type)
if arg_sets and arg_sets != [[]]:
raise ValueError(&No arguments to --%s allowed when multiple &
&files are specified& % operation_type)
elif arg_sets:
if 'divide' in operation_type and len(files) != 2:
raise ValueError(&Exactly 2 files are expected with --%s; &
&%i given& % (operation_type, len(files)))
for path, folders, objects in walk_rootfile(files[0]):
for obj in objects:
hists = [x.GetDirectory(path).Get(obj) for x in files]
if not alltrue([x and x.InheritsFrom('TH1')
for x in hists]):
math_func = globals()[operation_type]
math_func(outfile, joined(path, obj), hists)
outfile.Close()
Example 46
From project thumper-master,
under directory ,
in source file thumper.py.
def get_args():
parser = argparse.ArgumentParser(
description='Thumper - fast mass image thumbnail generator',
epilog='''Specify the thumbnail size in one of two ways. Use --size if you
intend a square thumbnail. Thumper will automatically fill the
thumbnail within a square of that many pixels, using it as height if
it's tall and skinny, or width if it is short and squat.
Alternatively, use both the --width and --height options. You must use
the image will be thumbnailed into this rectangle.
formatter_class=argparse.RawDescriptionHelpFormatter,
parser.add_argument('src_dir',
help='Directory containing source images')
parser.add_argument('dest_dir',
help='Directory to create and write thumbnails in')
parser.add_argument('--size', default=None, type=int,
help='Thumbnail size (max dimension, height or width) in pixels')
parser.add_argument('--width', default=None, type=int,
help='Max thumbnail width in pixels')
parser.add_argument('--height', default=None, type=int,
help='Max thumbnail height in pixels')
parser.add_argument('--processes', default=None, type=int,
help='Number of worker processes. Default is # of cores/cpus on the system')
args = parser.parse_args()
# check for correct arg combos
if args.size is None:
if args.width is None or args.height is None:
parser.error('You must specify the thumbnail size - either via --size, or via --width AND --height.')
if not (args.width is None and args.height is None):
parser.error('If you use --size, you can\'t use --width or --height.')
# check for sensible values
if args.size is not None and args.size &= 0:
parser.error('Thumbnail size must be a positive number.')
if args.width is not None and args.width &= 0:
parser.error('Thumbnail width must be a positive number.')
if args.height is not None and args.height &= 0:
parser.error('Thumbnail height must be a positive number.')
return args
Example 47
From project sick-master,
under directory sick,
in source file core.py.
def main(args=None):
config = ConfigParser()
config.read(['sick.ini', os.path.expanduser('~/.sick.ini'),
os.path.expanduser('~/.config/sick/sick.ini')])
sick_config = config['sick']
except KeyError:
sick_config = {}
except AttributeError:
sick_config = dict(config.items('sick'))
except NoSectionError:
sick_config = {}
parser = argparse.ArgumentParser()
default_host = sick_config.get('host')
host_required = default_host is None
default_api_key = sick_config.get('api_key')
api_key_required = default_api_key is None
parser.add_argument('--host', default=default_host, required=host_required)
parser.add_argument('--api_key', default=default_api_key,
required=api_key_required)
parser.add_argument('args', nargs='*')
parsed = vars(parser.parse_args(args))
host = parsed.pop('host')
api_key = parsed.pop('api_key')
sick = Sick(host, api_key)
input_args = parsed.pop('args')
num_args = len(input_args)
if num_args == 0:
cmd = 'shows'
parsed['tvdbid'] = int(input_args[0])
except Exception:
parsed['tvdbid'] = sick.find_tvdbid(input_args[0])
if num_args == 1:
cmd = 'episodes'
cmd = 'episode'
parsed['episode'] = parse_episode(input_args[1])
return getattr(sick, cmd)(**parsed)
except ErrorPrintAsIs as e:
print(e, file=sys.stderr)
except TvDbIdNotFound as e:
print('Could not find TVDB id for {}'.format(e), file=sys.stderr)
Example 48
From project pplacer,
under directory scripts,
in source file add_classifications.py.
def main():
logging.basicConfig(
, format=&%(levelname)s: %(message)s&)
parser = argparse.ArgumentParser(
description=&Add classifications to a database.&)
parser.add_argument('refpkg', type=Refpkg,
help=&refpkg containing input taxa&)
parser.add_argument('classification_db', type=sqlite3.connect,
help=&output sqlite database&)
parser.add_argument('classifications', type=argparse.FileType('r'), nargs='?',
default=sys.stdin, help=&input query sequences&)
args = parser.parse_args()
('loading taxonomy')
taxtable = TaxNode.from_taxtable(args.refpkg.open_resource('taxonomy', 'rU'))
rank_order = {rank: e for e, rank in enumerate(taxtable.ranks)}
def full_lineage(node):
rank_iter = reversed(taxtable.ranks)
for n in reversed(node.lineage()):
n_order = rank_order[n.rank]
yield n, list(itertools.takewhile(lambda r: rank_order[r] &= n_order, rank_iter))
def multiclass_rows(placement_id, seq, taxa):
ret = collections.defaultdict(float)
likelihood = 1. / len(taxa)
for taxon in taxa:
for node, want_ranks in full_lineage(taxtable.get_node(taxon)):
for want_rank in want_ranks:
ret[placement_id, seq, want_rank, node.rank, node.tax_id] += likelihood
for k, v in sorted(ret.items()):
yield k + (v,)
curs = args.classification_db.cursor()
curs.execute('INSERT INTO runs (params) VALUES (?)', (' '.join(sys.argv),))
run_id = curs.lastrowid
('inserting classifications')
for (name, mass), rows in group_by_name_and_mass(csv.DictReader(args.classifications)):
curs.execute('INSERT INTO placements (classifier, run_id) VALUES (&csv&, ?)', (run_id,))
placement_id = curs.lastrowid
curs.execute(
'INSERT INTO placement_names (placement_id, name, origin, mass) VALUES (?, ?, ?, ?)',
(placement_id, name, args.classifications.name, mass))
taxa = [row['tax_id'] for row in rows]
curs.executemany('INSERT INTO multiclass VALUES (?, ?, ?, ?, ?, ?)',
multiclass_rows(placement_id, name, taxa))
('cleaning up `multiclass` table')
curs.execute(&&&
CREATE TEMPORARY TABLE duplicates AS
SELECT name
FROM multiclass
JOIN placements USING (placement_id)
GROUP BY name
HAVING SUM(run_id = ?)
AND COUNT(DISTINCT run_id) & 1
&&&, (run_id,))
curs.execute(&&&
DELETE FROM multiclass
WHERE (SELECT run_id
FROM placements p
WHERE p.placement_id = multiclass.placement_id) && ?
AND name IN (SELECT name
FROM duplicates)
&&&, (run_id,))
args.mit()
Example 49
From project FanFicFare-master,
under directory included_dependencies/chardet,
in source file chardetect.py.
def main(argv=None):
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
# Get command line arguments
parser = argparse.ArgumentParser(
description=&Takes one or more file paths and reports their detected \
encodings&,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
conflict_handler='resolve')
parser.add_argument('input',
help='File whose encoding we would like to determine.',
type=argparse.FileType('rb'), nargs='*',
default=[sys.stdin])
parser.add_argument('--version', action='version',
version='%(prog)s {0}'.format(__version__))
args = parser.parse_args(argv)
for f in args.input:
if f.isatty():
print(&You are running chardetect interactively. Press & +
&CTRL-D twice at the start of a blank line to signal the & +
&end of your input. If you want help, run chardetect & +
&--help\n&, file=sys.stderr)
print(description_of(f, f.name))
Example 50
From project pyromaths-master,
under directory src,
in source file testexo.py.
def argument_parser():
&&&Return an argument parser&&&
parser = argparse.ArgumentParser()
parser.add_argument(
'-v', '--version',
action='version',
version='%(prog)s {version}'.format(version=VERSION),
subparsers = parser.add_subparsers(title='Commands', dest='command')
subparsers.required = True
subparsers.dest = 'command'
create = subparsers.add_parser(
help='Create test given in argument. If not, create missing tests.',
formatter_class=argparse.RawDescriptionHelpFormatter,
create.add_argument(
&exercise&,
metavar='EXERCISE[:SEED[,SEED]]',
nargs='*', type=exercise_argument, default=None,
help='Exercices to test. If empty, all exercises are tested.'
remove = subparsers.add_parser(
help='Remove a test',
remove.add_argument(
&exercise&,
metavar='EXERCISE[:SEED[,SEED]]',
nargs='+', type=exercise_argument, default=None,
help='Exercices to remove.',
update = subparsers.add_parser(
&Perform tests given in argument. &
&Update tests that have changed.&
formatter_class=argparse.RawDescriptionHelpFormatter,
update.add_argument(
&exercise&,
metavar='EXERCISE[:SEED[,SEED]]',
nargs='*', type=exercise_argument, default=None,
help='Exercices to test. If empty, all exercises are tested.'
compile_parser = subparsers.add_parser(
'compile',
help='Compile some exercises.',
formatter_class=argparse.RawDescriptionHelpFormatter,
compile_parser.add_argument(
&exercise&,
metavar='EXERCISE[:SEED[,SEED]]',
nargs='*', type=exercise_argument, default=None,
help='Exercices to compile. If empty, all exercises are compiled.'
check = subparsers.add_parser(
&Test exercises (equivalent to `python -m unittest discover`, &
&for exercises only).&
formatter_class=argparse.RawDescriptionHelpFormatter,
check.add_argument(
&exercise&,
metavar='EXERCISE[:SEED[,SEED]]',
nargs='*', type=exercise_argument, default=None,
help='Exercices to check. If empty, all exercises are checked.'
return parser
Example 51
From project mininet-wifi-master,
under directory util/vm,
in source file build.py.
def parseArgs():
&Parse command line arguments and run&
global LogToConsole, NoKVM, Branch, Zip, TIMEOUT, Forward
parser = argparse.ArgumentParser( description='Mininet VM build script',
epilog=buildFlavorString() + ' ' +
testString() )
parser.add_argument( '-v', '--verbose', action='store_true',
help='send VM output to console rather than log file' )
parser.add_argument( '-d', '--depend', action='store_true',
help='install dependencies for this script' )
parser.add_argument( '-l', '--list', action='store_true',
help='list valid build flavors and tests' )
parser.add_argument( '-c', '--clean', action='store_true',
help='clean up leftover build junk (e.g. qemu-nbd)' )
parser.add_argument( '-q', '--qcow2', action='store_true',
help='save qcow2 image rather than deleting it' )
parser.add_argument( '-n', '--nokvm', action='store_true',
help=&Don't use kvm - use tcg emulation instead& )
parser.add_argument( '-m', '--memory', metavar='MB', type=int,
default=1024, help='VM memory size in MB' )
parser.add_argument( '-i', '--image', metavar='image', default=[],
action='append',
help='Boot and test an existing VM image' )
parser.add_argument( '-t', '--test', metavar='test', default=[],
action='append',
help='specify a test to run' )
parser.add_argument( '-w', '--timeout', metavar='timeout', type=int,
default=0, help='set expect timeout' )
parser.add_argument( '-r', '--run', metavar='cmd', default='',
help='specify a command line to run before tests' )
parser.add_argument( '-p', '--post', metavar='cmd', default='',
help='specify a command line to run after tests' )
parser.add_argument( '-b', '--branch', metavar='branch',
help='branch to install and/or check out and test' )
parser.add_argument( 'flavor', nargs='*',
help='VM flavor(s) to build (e.g. raring32server)' )
parser.add_argument( '-z', '--zip', action='store_true',
help='archive .ovf and .vmdk into .zip file' )
parser.add_argument( '-o', '--out',
help='output file for test image (vmdk)' )
parser.add_argument( '-f', '--forward', default=[], action='append',
help='forward VM ports to local server, e.g. tcp:5555::22' )
args = parser.parse_args()
if args.depend:
if args.list:
print buildFlavorString()
if args.clean:
if args.verbose:
LogToConsole = True
if args.nokvm:
NoKVM = True
if args.branch:
Branch = args.branch
if args.zip:
Zip = True
if args.timeout:
TIMEOUT = args.timeout
if args.forward:
Forward = args.forward
if not args.test and not args.run and not args.post:
args.test = [ 'sanity', 'core' ]
for flavor in args.flavor:
if flavor not in isoURLs:
print &Unknown build flavor:&, flavor
print buildFlavorString()
build( flavor, tests=args.test, pre=args.run, post=args.post,
memory=args.memory )
except Exception as e:
log( '* BUILD FAILED with exception: ', e )
for image in args.image:
bootAndRun( image, runFunction=runTests, tests=args.test, pre=args.run,
post=args.post, memory=args.memory, outputFile=args.out,
uninstallNtpd=True
if not ( args.depend or args.list or args.clean or args.flavor
or args.image ):
parser.print_help()
Example 52
From project sagenb,
under directory util,
in source file translations.py.
def parser(self):
&&&the `argparse` parser
parser = argparse.ArgumentParser(
description='Localization management for sage notebook',
epilog='This command does nothing without additional options.\n'
'To see options available for every subcommand, type:\n'
{} SUBCOMMAND -h'.format(self.mand_name),
pot_parser = argparse.ArgumentParser(add_help=False)
pot_parser.add_argument(
dest='pot',
action='store_true',
help='Perform ACTION on sage message.pot file\n',
langs_parser = argparse.ArgumentParser(add_help=False)
langs_parser.add_argument(
'--langs', '--nolangs',
dest='langs',
action=LangsAction,
nargs='*',
choices=self.data.langs,
default=set(),
metavar=('xx_XX', 'yy_YY'),
help='--langs - add all available langs\n'
'--langs xx_XX ... - add selected langs\n'
'--nolangs - remove all langs processing\n'
'--nolangs xx_XX ... - remove selected langs\n'
'no language is processed by default.\n'
'Examples:\n'
To process only spanish and french:\n'
translations.py ACTION --langs es_ES fr_FR\n'
To process all but spanish and french:\n'
translations.py ACTION --langs --nolangs es_ES fr_FR\n'
backup_parser = argparse.ArgumentParser(add_help=False)
backup_parser.add_argument(
'--nobackup',
dest='backup',
action='store_false',
help='Deactivate backup for processed files\n',
subparsers = parser.add_subparsers(
metavar='SUBCOMMAND',
title='subcommands',
description='',
help='is one of:',
parser_update = subparsers.add_parser(
'update', parents=(pot_parser, langs_parser, backup_parser),
help='update pot and/or po files from sources',
description='update pot and/or po files from source tree',
epilog='Warning: If backup is active, previous backup files '
'are overwritten',
formatter_class=argparse.RawTextHelpFormatter,
parser_update.add_argument(
'--nowarn',
dest='warn',
action='store_false',
help='Prevent warning about fuzzy, untranslated and\n'
'obsolete messages to be printed',
parser_update.add_argument(
'--fuzzy',
dest='nofuzzy',
action='store_false',
help='Fuzzy matching of message IDs\n',
parser_update.set_defaults(func=self.update)
parser_extract = subparsers.add_parser(
'extract', parents=(backup_parser,),
help='extract a new pot file from sources',
description='extract a new message.pot template

我要回帖

更多关于 python3中文帮助文档 的文章

 

随机推荐