def parse_arguments(self):
self.arguments = docopt(__doc__)
self.parguments = self.get_provided_arguments()
if not self.parguments:
format_help(__doc__, None)
exit(0)
elif '--version' in self.parguments:
print(__version__)
exit(0)
elif '--get-list' in self.parguments:
[print(module) for module in list_wg_modules()]
exit(0)
elif '--list' in self.parguments or '--search' in self.parguments:
if '--target' in self.parguments:
self.we_get_run = 1
if self.we_get_run != 1:
format_help(__doc__, "Use --search/--list with --target.")
exit(1)
python类docopt()的实例源码
def main():
opts = docopt.docopt(__doc__)
radius = float(opts['<RADIUS>'])
nlines = int(opts['<NUM_LINES>'], 0)
npoints = int(opts['<NUM_POINTS>'], 0)
outfilename = opts['<OUTFILE>']
if not outfilename:
outfilename = 'os_%f_%d_%d.ngc' % (radius, nlines, npoints)
logging.getLogger('MainApp').info('Gcode file name: %s' % (outfilename))
p = OldSchoolPattern(radius=radius, nlines=nlines, npoints=npoints)
s = PathSimplifier()
comment = '''Generated by oldschool.py with parameters:
Radius: %f
Number of lines: %d
Number of points/line: %d''' % (radius, nlines, npoints)
g = GCodeGenerator(open(outfilename, 'w'), comment)
p.giterate(s.add_vector)
vectors = s.simplify()
#
# adjust all vectors to be negative only
#
vectors = add_to_vectors(vectors, -Point(radius, radius))
g.generate(vectors)
def _main(argv):
"""The main function for the 'task' subcommand"""
# We must special case the 'dcos task exec' subcommand in order to
# allow us to pass arguments to docopt in a more user-friendly
# manner. Specifically, we need to be able to to pass arguments
# beginning with "-" to the command we are trying to launch with
# 'exec' without docopt trying to match them to a named parameter
# for the 'dcos' command itself.
if len(argv) > 1 and argv[1] == "exec":
args = docopt_wrapper(
default_doc("task_exec"),
default_doc("task"),
argv=argv[2:],
version="dcos-task version {}".format(dcoscli.version),
options_first=True,
base_subcommand="task",
subcommand="exec")
else:
args = docopt.docopt(
default_doc("task"),
argv=argv,
version="dcos-task version {}".format(dcoscli.version))
return cmds.execute(_cmds(), args)
def main():
"""Main CLI entrypoint."""
options = docopt(__doc__, version=VERSION)
setup_logger(options.get('--verbose', False))
priority_order = ["cycle", "asg", "instances", "deploy", "patch", "toggle", "upstream", "publish", "verify", "service"]
cmd_opts = options.copy()
if cmd_opts["<service>"] is not None:
cmd_opts["service"] = True
for cmd in priority_order:
if cmd_opts[cmd]:
logging.info('Running {0} command'.format(cmd))
CommandClass = commands[cmd]
command = CommandClass(options)
return command.run()
print("Unknown command")
# Allow local execution for debugging
def main():
arguments = docopt(__doc__,version = '1.0.0')
target = arguments['<target>']
timeout = int(arguments['--timeout'])
thread_num = int(arguments['<thread_num>'])
process_num = int(arguments['<process_num>'])
print('{} {} {} {}'.format(target,timeout,thread_num,process_num))
validator = Validator(target,timeout,process_num,thread_num)
ip_all=[]
logging.info("Load proxy ip, total: %s", len(ip_all))
result_tmp = validator.run(ip_all)
result=[]
for one in result_tmp:
if one["speed"] > 8:
pass
else:
result.append(one)
logging.info("validator run finished")
logging.info(len(result))
result = sorted(result, key=lambda x: x["speed"])
return result
def _main():
args = docopt(__doc__, version="1")
print("Loading courses...")
courses = json.load(open(args['--file']), object_pairs_hook=OrderedDict)
college = args['<college>']
course_number = args['<course_number>']
for matching_course in get_course_instances(courses, college, course_number):
print(get_term(matching_course))
print(matching_course['title'])
max_teach_len = max(map(len, (x['Instructor'] for x in matching_course['sections'].values() if 'Instructor' in x)))
for section_number, section in matching_course['sections'].items():
if 'Instructor' in section:
print("Section {} - {:<{}s} ({}/{})"
.format(section_number,
section['Instructor'],
max_teach_len,
section['Enrolled'],
section['Class Max']))
print("")
def render(_argv=None, _path=None, _print=print):
args = docopt.docopt(__doc__, argv=_argv,
version='git-literate-render {}'.format(__version__))
repo_path = _path or os.getcwd()
repo = repo_for_path(repo_path)
sections = literategit.list_from_range(repo,
args['<begin-commit>'],
args['<end-commit>'])
import_name, obj_name = args['<create-url>'].rsplit('.', 1)
try:
create_url_module = importlib.import_module(import_name)
except ImportError:
import sys
sys.path.append(repo_path)
create_url_module = importlib.import_module(import_name)
create_url = getattr(create_url_module, obj_name)
_print(literategit.render(sections, create_url, args['<title>']))
def decrypt_secret_cmd():
arguments = docopt(__doc__, options_first=True)
secret = StrictSecret(arguments['<secret>'])
print(secret.decrypt().decode('utf-8'))
def encrypt_secret_cmd():
arguments = docopt(__doc__, options_first=True)
encrypt_params = dict()
if arguments['kms']:
from secretcrypt import kms
encrypt_params = dict(
region=arguments['--region'],
key_id=arguments['<key_id>'],
)
module = kms
elif arguments['local']:
from secretcrypt import local
module = local
elif arguments['plain']:
from secretcrypt import plain
module = plain
elif arguments['password']:
from secretcrypt import password
module = password
if arguments['--multiline']:
plaintext = sys.stdin.read()
else:
# do not print prompt if input is being piped
if sys.stdin.isatty():
print('Enter plaintext: ', end="", file=sys.stderr),
sys.stderr.flush()
stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
plaintext = stdin.readline().rstrip(b'\n')
secret = encrypt_secret(module, plaintext, encrypt_params)
print(secret)
def main():
args = docopt(__doc__)
# Parse args
inp = args['--in']
out = args['--out']
include_id = args["--id"] is not None
logging.info("Loading spaCy...")
pe = prop_extraction(include_id)
# Differentiate between single input file and directories
if os.path.isdir(inp):
logging.debug('Running on directories:')
num_of_lines = num_of_extractions = 0
for input_fn in glob(os.path.join(inp, '*.txt')):
output_fn = os.path.join(out, path_leaf(input_fn).replace('.txt', '.prop'))
logging.debug('input file: {}\noutput file:{}'.format(input_fn, output_fn))
cur_line_counter, cur_extractions_counter = run_single_file(input_fn, output_fn, pe)
num_of_lines += cur_line_counter
num_of_extractions += cur_extractions_counter
else:
logging.debug('Running on single files:')
num_of_lines, num_of_extractions = run_single_file(inp, out, pe)
logging.info('# Sentences: {} \t #Extractions: {} \t Extractions/sentence Ratio: {}'.
format(num_of_lines, num_of_extractions, float(num_of_extractions) / num_of_lines))
def start(self, override_docopt=None) :
try :
self._install_signal_handlers()
options = docopt(__doc__, version=shift_detect.__version__)
self._front_matter(options)
except Exception as e :
print("ERROR: Caught {} : {}".format(type(e), e), file=sys.stderr)
sys.exit(1)
def main():
arguments = docopt.docopt(__doc__)
# Run training
seed = 0 # Use a seed of zero (you may want to randomize the seed!)
env = get_env(arguments['--envid'], seed)
with get_session() as session:
model = arguments['--model'].lower()
num_filters = int(arguments['--num-filters'])
batch_size = int(arguments['--batch-size'])
print(' * [INFO] %s model (Filters: %d, Batch Size: %d)' % (
model, num_filters, batch_size))
save_path = atari_learn(
env,
session,
num_timesteps=int(arguments['--timesteps']),
num_filters=num_filters,
model=model,
batch_size=batch_size,
restore=arguments['--restore'],
checkpoint_dir=arguments['--ckpt-dir'],
learning_starts=arguments['--learning-starts'])
reader = tf.train.NewCheckpointReader(save_path)
W = reader.get_tensor('q_func/action_value/fully_connected/weights')
print('Largest entry:', np.linalg.norm(W, ord=np.inf))
print('Frobenius norm:', np.linalg.norm(W, ord='fro'))
def main():
args = docopt(__doc__, version='flashcard 0.0.4')
if args['<flashcard>'].startswith("https://docs.google.com/spreadsheets/"):
flashcard = fetch_google_spreadsheet(args['<flashcard>'])
else:
print("<flashcard> should be URL of Google Spreadsheet (other sources are TBA)")
exit(1)
hint_rate = None
if args['--hint'] is not None:
hint_rate = float(args['--hint'])
assert 0.0 <= hint_rate <= 1.0, "hint rate should satisfy 0.0 <= hint_rate <= 1.0"
run(flashcard, hint_rate)
def main():
opt = docopt.docopt(__opt__ % {'prog': os.path.basename(sys.argv[0])})
verbose = opt['--verbose']
logging.getLogger().setLevel(getattr(logging, (
'ERROR',
'WARNING',
'INFO',
'DEBUG',
)[min(verbose, 3)]))
logging.debug(opt)
sys.exit(entry(opt))
def main():
try:
args = docopt(__doc__, version='Wurst CLI 0.1.dev')
if args['cleanup']:
cleanup_data_directory()
elif args['show']:
pass
else:
raise ValueError
except KeyboardInterrupt:
sys.exit(1)
def cliparser(func):
"""
This decorator is used to simplify the try/except block and pass the result
of the docopt parsing to the called action.
"""
def fn(self, arg):
try:
opt = docopt(fn.__doc__, arg)
except DocoptExit as e:
# The DocoptExit is thrown when the args do not match.
# We print a message to the user and the usage block.
print('Invalid Command!')
print(e)
return
except SystemExit:
# The SystemExit exception prints the usage for --help
# We do not need to do the print here.
return
return func(self, opt)
fn.__name__ = func.__name__
fn.__doc__ = func.__doc__
fn.__dict__.update(func.__dict__)
return fn
def main():
args = docopt(__doc__, version='0.1')
debug = args["--debug"]
verbose = args["--verbose"]
if not os.path.exists("log"):
os.makedirs("log")
configure_logging("log/lama_api.log", debug=debug, verbose=verbose)
cmd_line = "COMMAND : "+" ".join(sys.argv)
logging.info(cmd_line)
try:
Lamadb.create_db()
LamaFtp.create_ftp()
run_api(debug=debug)
except KeyboardInterrupt:
Analyzer.stop_analyzer()
def main():
args = docopt(__doc__, version='0.1')
debug = args["--debug"]
verbose = args["--verbose"]
if not os.path.exists("log"):
os.makedirs("log")
configure_logging("log/lama_analyzer.log", debug=debug, verbose=verbose)
cmd_line = "COMMAND : "+" ".join(sys.argv)
logging.info(cmd_line)
try:
Lamadb.create_db()
LamaFtp.create_ftp()
Analyzer.run_analyzer()
except KeyboardInterrupt:
Analyzer.stop_analyzer()
def main():
args = docopt(__doc__, version='0.1')
debug = args["--debug"]
verbose = args["--verbose"]
if not os.path.exists("log"):
os.makedirs("log")
configure_logging("log/lama_dispatcher.log", debug=debug, verbose=verbose)
cmd_line = "COMMAND : "+" ".join(sys.argv)
logging.info(cmd_line)
try:
Lamadb.create_db()
LamaFtp.create_ftp()
Dispatcher.dispatch()
except KeyboardInterrupt:
Dispatcher.stop_dispatch()
def main():
args = docopt(__doc__, version='0.1')
debug = args["--debug"]
verbose = args["--verbose"]
if not os.path.exists("log"):
os.makedirs("log")
configure_logging("log/lama_mail.log", debug=debug, verbose=verbose)
cmd_line = "COMMAND : "+" ".join(sys.argv)
logging.info(cmd_line)
config = configparser.ConfigParser()
config.read('lama/conf/project.conf')
try:
user = config["MAIL_INPUT"]["user"]
password = config["MAIL_INPUT"]["password"]
server = config["MAIL_INPUT"]["server"]
port = config["MAIL_INPUT"]["port"]
except KeyError as e:
logging.error("Error project.conf[MAIL] : {} missing.".format(str(e)))
exit(1)
# overide params
if args["--user"]:
user = args["--user"]
if args["--server"]:
server = args["--server"]
if args["--port"]:
port = args["--port"]
if args["--password"]:
password = getpass.getpass("Enter password please : ")
print(user, password, server, port)
mail = Mail(user, password, server, port)
mail.run()