def __load_arguments(self):
parser = ArgsParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('ram_file', metavar='<RAM File>', action=FullPaths, type=parse_is_file,
help='path to the RAM file.')
parser.add_argument('overlay_dir', metavar='<Overlay Directory>', action=FullPaths, type=parse_is_dir,
help='path to the overlay directory.')
parser.add_argument('executable', metavar='<Info Executable>', action=FullPaths, type=parse_is_file,
help='path to the info executable (kernel address dumper).')
parser.add_argument('mem', metavar='<RAM Size>', help='size of virtual RAM (default: 300).', default=300, type=int)
parser.add_argument('-v', required=False, help='enable verbose mode (./debug.log).', action='store_true',
default=False)
parser.add_argument('-S', required=False, metavar='Snapshot', help='specifiy snapshot title (default: kafl).', default="kafl", type=str)
parser.add_argument('-macOS', required=False, help='enable macOS Support (requires Apple OSK)', action='store_true', default=False)
self.argument_values = vars(parser.parse_args())
python类RawTextHelpFormatter()的实例源码
def main():
parser = argparse.ArgumentParser(description='test', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'-a', '--attribute',
default='Smiling',
type=str,
help='Specify attribute name for training. \ndefault: %(default)s. \nAll attributes can be found in list_attr_celeba.txt'
)
parser.add_argument(
'-g', '--gpu',
default='0',
type=str,
help='Specify GPU id. \ndefault: %(default)s. \nUse comma to seperate several ids, for example: 0,1'
)
args = parser.parse_args()
celebA = Dataset(args.attribute)
GeneGAN = Model(is_train=True)
run(config, celebA, GeneGAN, gpu=args.gpu)
def standard_parser(description="Confu configuration script"):
import argparse
from os import linesep
from confu.platform import host, possible_targets
parser = argparse.ArgumentParser(description=description,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--target", dest="target", metavar="PLATFORM", type=Platform,
default=host.name,
help="platform where the code will run. Potential options:" + linesep +
" " + host.name + " (default)" + linesep +
linesep.join(" " + target for target in possible_targets[1:]))
parser.add_argument("--toolchain", dest="toolchain", metavar="TOOLCHAIN",
choices=["auto", "gnu", "clang"], default="auto",
help="toolchain to use for compilation. Potential options:" + linesep +
linesep.join(" " + name for name in ["auto (default)", "gnu", "clang"]))
return parser
def __init__(self):
parser = argparse.ArgumentParser(
description='A CLI tool for mymodule',
formatter_class=argparse.RawTextHelpFormatter,
usage='%(prog)s command options',
allow_abbrev=False)
parser.add_argument('command', help='Command to run.')
args = parser.parse_args(sys.argv[1:2]) # Ignore options
self._one_func_mode = False
if not hasattr(self, args.command.replace('.', '_')):
print('Unrecognized command!')
sys.exit(1)
getattr(self, args.command.replace('.', '_'))()
def contruct_parser(subparsers):
parser = subparsers.add_parser('lswitch', description="Functions for logical switches",
help="Functions for logical switches",
formatter_class=RawTextHelpFormatter)
parser.add_argument("command", help="""
create: create a new logical switch
read: return the virtual wire id of a logical switch
delete: delete a logical switch"
list: return a list of all logical switches
""")
parser.add_argument("-t",
"--transport_zone",
help="nsx transport zone")
parser.add_argument("-n",
"--name",
help="logical switch name, needed for create, read and delete")
parser.set_defaults(func=_lswitch_main)
def parse_args():
"""Parse arguments from the command line"""
parser = argparse.ArgumentParser(description=DESC_MSG,
formatter_class=RawTextHelpFormatter)
group_exc = parser.add_mutually_exclusive_group(required=False)
group_exc.add_argument('-g', '--debug', dest='debug', action='store_true')
group_exc.add_argument('-l', '--info', dest='info', action='store_true')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + VERSION)
subparsers = parser.add_subparsers(dest='subparser_name')
add_mapping_subparser(subparsers)
add_panel_subparser(subparsers)
add_csv_subparser(subparsers)
return parser.parse_args()
def main(args=None):
parser = ArgumentParser(description='HAR to WARC Converter',
formatter_class=RawTextHelpFormatter)
parser.add_argument('input')
parser.add_argument('output')
parser.add_argument('--title')
parser.add_argument('--no-z', action='store_true')
parser.add_argument('-v', '--verbose', action='store_true')
r = parser.parse_args(args=args)
rec_title = r.title or r.input.rsplit('/', 1)[-1]
logging.basicConfig(format='[%(levelname)s]: %(message)s')
HarParser.logger.setLevel(logging.ERROR if not r.verbose else logging.INFO)
with open(r.output, 'wb') as fh:
writer = WARCWriter(fh, gzip=not r.no_z)
HarParser(r.input, writer).parse(r.output, rec_title)
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--credentials', type=existing_file,
metavar='OAUTH2_CREDENTIALS_FILE',
default=os.path.join(
os.path.expanduser('~/.config'),
'google-oauthlib-tool',
'credentials.json'
),
help='Path to store and read OAuth2 credentials')
args = parser.parse_args()
with open(args.credentials, 'r') as f:
credentials = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
with Assistant(credentials) as assistant:
for event in assistant.start():
process_event(event)
allocate_ip_addresses.py 文件源码
项目:cluster-genesis
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def main():
parser = argparse.ArgumentParser(
description=('Allocates IP addresses on nodes in an inventory file.'),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--inventory',
dest='inventory_file',
required=True,
help='The path to the inventory file.')
# Handle error cases before attempting to parse
# a command off the command line
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
allocate_ips(args.inventory_file)
def parse_argument(argv=None):
parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
parser.set_defaults(body=None, headers={})
make_positional_argument(parser)
make_troubleshooting_argument(parser)
args = parser.parse_args(sys.argv[1:] if argv is None else argv)
if args.debug:
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
log.addHandler(handler)
log.setLevel(logging.DEBUG)
set_url_info(args)
set_request_data(args)
return args
def parse_argument(argv=None):
parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
parser.set_defaults(body=None, headers={})
make_positional_argument(parser)
make_troubleshooting_argument(parser)
args = parser.parse_args(sys.argv[1:] if argv is None else argv)
if args.debug:
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
log.addHandler(handler)
log.setLevel(logging.DEBUG)
set_url_info(args)
set_request_data(args)
return args
def main():
version = pkg_resources.require('hls2dash')[0].version
parser = argparse.ArgumentParser(
description="Rewrap a MPEG2 TS segment to a fragmented MP4"
,formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('tsfile', metavar='TSFILE', help='Path to TS file. Can be a URI or local file.')
parser.add_argument('output', metavar='OUTPUT', help='Output file name')
parser.add_argument('--outdir', dest='outdir', default='.', help='Directory where the fragmented MP4 will be stored. Default is current directory')
parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Write debug info to stderr')
parser.add_argument('--version', action='version', version='%(prog)s ('+version+')')
args = parser.parse_args()
debug.doDebug = args.debug
ts = None
if re.match('^http', args.tsfile):
ts = TS.Remote(args.tsfile)
else:
ts = TS.Local(args.tsfile)
ts.remuxMP4(args.outdir, args.output)
def main():
version = VERSION()
parser = argparse.ArgumentParser(
description="Generate single and multi period MPEG DASH manifest from a live HLS source.\n"
"Writes MPEG DASH manifest to stdout.\n\n"
"Currently assumes that HLS variant is named as 'master[PROFILE].m3u8'\n"
" master2500.m3u8, master1500.m3u8\n"
"and that the segments are named as 'master[PROFILE]_[SEGNO].ts'\n"
" master2500_34202.ts, master1500_34202.ts\n"
,formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('playlist', metavar='PLAYLIST', help='Path to HLS playlist file. Can be a URI or local file.')
parser.add_argument('--multi', dest='multi', action='store_true', default=False, help='Generate multi period MPEG DASH on EXT-X-CUE markers in HLS')
parser.add_argument('--ctx', dest='ctx', default=None, help='Name of DASH session file')
parser.add_argument('--ctxdir', dest='ctxdir', default='/tmp/', help='Where to store DASH session file. Defaults to /tmp/')
parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Write debug info to stderr')
parser.add_argument('--version', action='version', version='%(prog)s ('+version+')')
args = parser.parse_args()
debug.doDebug = args.debug
mpd = MPD.HLS(args.playlist, args.multi, args.ctxdir, args.ctx)
mpd.setVersion(VERSION())
mpd.load()
print(mpd.asXML())
def create_parser():
"""
Creates the parser object
By using a function, the parser is also easily available for unittests
"""
class formatter_class(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawTextHelpFormatter):
pass
parser = argparse.ArgumentParser(formatter_class=formatter_class)
parser.add_argument(
'-v', '--verbose', action='store_true', default=False)
subparsers = parser.add_subparsers()
run.create_subparsers(subparsers)
merge.create_subparsers(subparsers)
datasets.create_subparser(subparsers)
new.create_subparsers(subparsers)
profile.create_subparsers(subparsers)
return parser
def _get_arg_parser(self, doc_parser=False):
description = textwrap.dedent(__doc__)
examples = textwrap.dedent('''
mdt-info-protocol my_protocol.prtcl
''')
epilog = self._format_examples(doc_parser, examples)
parser = argparse.ArgumentParser(description=description, epilog=epilog,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('protocol',
action=mdt.shell_utils.get_argparse_extension_checker(['.prtcl']),
help='the protocol file').completer = FilesCompleter(['prtcl'], directories=False)
return parser
def _get_arg_parser(self, doc_parser=False):
description = textwrap.dedent(__doc__)
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('items', metavar='items', type=str, nargs='*', help='the directory or file(s)',
default=None).completer = FilesCompleter()
parser.add_argument('-c', '--config', type=str,
help='Use the given initial configuration').completer = \
FilesCompleter(['conf'], directories=False)
parser.add_argument('-m', '--maximize', action='store_true', help="Maximize the shown window")
parser.add_argument('--to-file', type=str, help="If set export the figure to the given filename")
parser.add_argument('--width', type=int, help="The width of the output file when --to-file is set")
parser.add_argument('--height', type=int, help="The height of the output file when --to-file is set")
parser.add_argument('--dpi', type=int, help="The dpi of the output file when --to-file is set")
return parser
def _get_arg_parser(self, doc_parser=False):
description = textwrap.dedent(__doc__)
examples = textwrap.dedent('''
mdt-info-img my_img.nii
mdt-info-img *.nii
''')
epilog = self._format_examples(doc_parser, examples)
parser = argparse.ArgumentParser(description=description, epilog=epilog,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('images', metavar='images', nargs="+", type=str,
help="The input images")
return parser
def _get_arg_parser(self, doc_parser=False):
description = textwrap.dedent(__doc__)
examples = textwrap.dedent('''
mdt-apply-mask data.nii.gz -m roi_mask_0_50.nii.gz
mdt-apply-mask *.nii.gz -m my_mask.nii.gz
''')
epilog = self._format_examples(doc_parser, examples)
parser = argparse.ArgumentParser(description=description, epilog=epilog,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('mask', help='the (brain) mask to use').completer = \
FilesCompleter(['nii', 'gz', 'hdr', 'img'], directories=False)
parser.add_argument('input_files', metavar='input_files', nargs="+", type=str,
help="The input images to use")
parser.add_argument('--overwrite', dest='overwrite', action='store_true',
help="Overwrite the original images, if not set we create an output file.")
parser.set_defaults(overwrite=False)
return parser
def _get_arg_parser(self, doc_parser=False):
description = textwrap.dedent(__doc__)
examples = textwrap.dedent('''
mdt-generate-bvec-bval my_protocol.prtcl
mdt-generate-bvec-bval my_protocol.prtcl bvec_name.bvec bval_name.bval
''')
epilog = self._format_examples(doc_parser, examples)
parser = argparse.ArgumentParser(description=description, epilog=epilog,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('protocol', help='the protocol file').completer = FilesCompleter()
parser.add_argument('bvec', help="the output bvec file", nargs='?', default=None).completer = FilesCompleter()
parser.add_argument('bval', help="the output bvec file", nargs='?', default=None).completer = FilesCompleter()
return parser
def main(self, args):
import aetros.const
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' pull-job')
parser.add_argument('id', nargs='?', help="Model name like peter/mnist/ef8009d83a9892968097cec05b9467c685d45453")
parsed_args = parser.parse_args(args)
if not parsed_args.id:
parser.print_help()
sys.exit(1)
config = read_home_config()
model = parsed_args.id[0:parsed_args.id.rindex('/')]
ref = 'refs/aetros/job/' + parsed_args.id[parsed_args.id.rindex('/')+1:]
git_dir = os.path.normpath(config['storage_dir'] + '/' + model + '.git')
if not os.path.isdir(git_dir):
self.logger.error("Git repository for model %s in %s not found." % (parsed_args.id, git_dir))
self.logger.error("Are you in the correct directory?")
print('Pull ' + ref + ' into ' + git_dir)
setup_git_ssh(config)
subprocess.call([config['git'], '--bare', '--git-dir', git_dir, 'fetch', 'origin', ref+':'+ref])
def main(self, args):
from aetros.predict import predict
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' predict')
parser.add_argument('id', nargs='?', help='the job id, e.g. peter/mnist/5d0f81d3ea73e8b2da3236c93f502339190c7037')
parser.add_argument('--weights', help="Weights path. Per default we try to find it in the ./weights/ folder.")
parser.add_argument('-i', nargs='+', help="Input (path or url). Multiple allowed")
parser.add_argument('--th', action='store_true', help="Uses Theano instead of Tensorflow")
parsed_args = parser.parse_args(args)
if not parsed_args.id:
parser.print_help()
sys.exit()
if not parsed_args.i:
parser.print_help()
sys.exit()
os.environ['KERAS_BACKEND'] = 'theano' if parsed_args.th else 'tensorflow'
predict(self.logger, parsed_args.id, parsed_args.i, parsed_args.weights)
def main(self, args):
import aetros.const
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' server')
parser.add_argument('id', nargs='?', help='job id')
parser.add_argument('--weights', help="Weights path. Per default we try to find it in the ./weights/ folder or download it.")
parser.add_argument('--latest', action="store_true", help="Instead of best epoch we upload latest weights.")
parser.add_argument('--tf', action='store_true', help="Uses TensorFlow instead of Theano")
parser.add_argument('--port', help="Changes port. Default 8000")
parser.add_argument('--host', help="Changes host. Default 127.0.0.1")
parsed_args = parser.parse_args(args)
self.lock = Lock()
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
if not parsed_args.id:
parser.print_help()
sys.exit()
os.environ['KERAS_BACKEND'] = 'tensorflow' if parsed_args.tf else 'theano'
self.model = self.start_model(parsed_args)
self.start_webserver('127.0.0.1' if not parsed_args.host else parsed_args.host, 8000 if not parsed_args.port else int(parsed_args.port))
def main(self, args):
import aetros.const
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
prog=aetros.const.__prog__ + ' run')
parsed_args = parser.parse_args(args)
user = api.user()
print("Key installed of account %s (%s)" % (user['username'], user['name']))
if len(user['accounts']) > 0:
for orga in six.itervalues(user['accounts']):
print(" %s of organisation %s (%s)." % ("Owner" if orga['memberType'] == 1 else "Member", orga['username'], orga['name']))
else:
print(" Without membership to an organisation.")
def add_log_args(self):
"""
Add arguments for log manipulations
:return:
"""
self.log_parser = self.subparsers.add_parser('log', help="Manipulations for logs",
formatter_class=argparse.RawTextHelpFormatter)
self.log_parser.add_argument('action', choices=['list', 'get'])
# To get multiline help msgs:
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-in-the-help-text
self.log_parser.add_argument('--limit', '-l', type=int, default=100, required=False)
self.log_parser.add_argument('--device_list', '-n', type=str, required=False)
self.log_parser.add_argument('--begin', '-b', required=False)
self.log_parser.add_argument('--end', '-e', required=False)
# self.log_parser.add_argument('options', nargs='*', help='''key=value pairs used to assist in selecting
# and setting attributes
# More
# ... and more
# ...and more!''')
self.log_parser.set_defaults(func=self.log_execute)
def parse_args():
parser = ArgumentParser(
formatter_class=RawTextHelpFormatter, description=__doc__
)
parser.add_argument(
'--exe',
default='/usr/bin/pt-config-diff',
help='"pt-config-diff" executable (default: %(default)s)',
)
parser.add_argument(
'--host',
default='localhost',
help='Target MySQL server (default: %(default)s)',
)
parser.add_argument(
'--user',
help='MySQL user (default: %(default)s)'
)
parser.add_argument(
'--passwd',
help='MySQL password (default: %(default)s)'
)
parser.add_argument('conf_files', nargs='+')
return parser.parse_args()
def arg_parser():
parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
parser.add_argument("-u", "--update", action="store_true", default=False, help="Update character set")
parser.add_argument("--debug", action="store_true", default=False, help="Enable debug logging")
parser.add_argument("-d", "--domain", default=None, help="Domain without prefix and suffix. (google)")
parser.add_argument("-s", "--suffix", default=None, help="Suffix to check alternative domain names. (.com, .net)")
parser.add_argument("-c", "--count", default=1, help="Character count to change with punycode alternative (Default: 1)")
parser.add_argument("-os", "--original_suffix", default=None,
help="Original domain to check for phisihing\n"
"Optional, use it with original port to run phishing test")
parser.add_argument("-op", "--original_port", default=None, help="Original port to check for phisihing\n"
"Optional, use it with original suffix to run phishing test")
parser.add_argument("-f", "--force", action="store_true", default=False,
help="Force to calculate alternative domain names")
parser.add_argument("-t", "--thread", default=15, help="Thread count")
return parser.parse_args()
def main():
"""Run example queries."""
parser = argparse.ArgumentParser(
description='Wrapper for Annotation Detection.',
formatter_class=argparse.RawTextHelpFormatter)
required = parser.add_argument_group('Required arguments:')
required.add_argument('-o',
help='Output directory for test results.',
required=True,
type=str)
args = parser.parse_args()
print('Alerts testing...')
test_alerts(args.o)
print('Cameras testing...')
test_cameras(args.o)
print('Observations testing...')
test_observations(args.o)
print('Collections testing...')
test_collections(args.o)
print('COMPLETE')
def _parse_input_parameters(self):
"""
Set the configuration for the Logger
"""
Global.LOGGER.debug("define and parsing command line arguments")
parser = argparse.ArgumentParser(
description='A workflow engine for Pythonistas', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('FILENAME', nargs='+',help='name of the recipe file(s)')
parser.add_argument('-i', '--INTERVAL', type=int, default=500,
metavar=('MS'),
help='perform a cycle each [MS] milliseconds. (default = 500)')
parser.add_argument('-m', '--MESSAGEINTERVAL', type=int,
metavar=('X'),
help='dequeue a message each [X] tenth of milliseconds. (default = auto)')
parser.add_argument('-s', '--STATS', type=int, default=0,
metavar=('SEC'),
help='show stats each [SEC] seconds. (default = NO STATS)')
parser.add_argument('-t', '--TRACE', action='store_true',help='enable super verbose output, only useful for tracing')
parser.add_argument('-v', '--VERBOSE', action='store_true',help='enable verbose output')
parser.add_argument('-V', '--VERSION',
action="version", version=__version__)
args = parser.parse_args()
return args
def main():
lib_lst = [section['section_name'] for section in get_libraries_table()]
parser = argparse.ArgumentParser(description="Use PlexPy to pull plays by library",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-l', '--libraries', nargs='+', type=str, choices=lib_lst, metavar='',
help='Space separated list of case sensitive names to process. Allowed names are: \n'
'(choices: %(choices)s)')
opts = parser.parse_args()
for section in get_libraries_table(opts.libraries):
sec_name = section['section_name']
sec_plays = section['plays']
print(OUTPUT.format(section=sec_name, plays=sec_plays))
def parse_args():
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description=\
"Usage: python brutespray.py <OPTIONS> \n")
menu_group = parser.add_argument_group(colors.lightblue + 'Menu Options' + colors.normal)
menu_group.add_argument('-f', '--file', help="GNMAP or XML file to parse", required=True)
menu_group.add_argument('-o', '--output', help="Directory containing successful attempts", default="brutespray-output")
menu_group.add_argument('-s', '--service', help="specify service to attack", default="all")
menu_group.add_argument('-t', '--threads', help="number of medusa threads", default="2")
menu_group.add_argument('-T', '--hosts', help="number of hosts to test concurrently", default="1")
menu_group.add_argument('-U', '--userlist', help="reference a custom username file", default=None)
menu_group.add_argument('-P', '--passlist', help="reference a custom password file", default=None)
menu_group.add_argument('-u', '--username', help="specify a single username", default=None)
menu_group.add_argument('-p', '--password', help="specify a single password", default=None)
menu_group.add_argument('-c', '--continuous', help="keep brute-forcing after success", default=False, action='store_true')
menu_group.add_argument('-i', '--interactive', help="interactive mode", default=False, action='store_true')
argcomplete.autocomplete(parser)
args = parser.parse_args()
return args