示例#1
0
def main(argv):
    """
    Interpret command line arguments and run the corresponding command.
    """
    # process command line arguments
    args = docopt(__doc__, argv=argv, version=__version__,
                  help=True, options_first=True)

    cmd = args['<command>']
    subargv = [cmd] + args['<args>']
    
    if cmd in COMMANDS:
        startup_check()

        handler = COMMANDS[cmd]
        if handler is None:
            raise NotImplementedError("Command not implemented.")
        else:
            handler(subargv)
    elif cmd == 'help':
        help_text(subargv)
    elif cmd == 'version':
        version_text(subargv)
    else:
        raise Exception("Invalid command: {cmd}".format(cmd=cmd))
示例#2
0
def main(wf):
    """Accept Alfred's args and pipe to workflow class"""
    argv = docopt(config.__usage__, argv=wf.args, version=config.__version__)
    log.info(wf.args)
    pd = ZotWorkflow(wf)
    res = pd.run(argv)
    if res:
        print(res)
示例#3
0
def main(argv):
    """
    Interpret command line arguments and run the corresponding command.
    """
    args = docopt(__doc__, argv=argv, help=True)

    pdb_path = args['PERSONAL_DB']
    if pdb_path == None:
        pdb_path = defs.DB_PERSONAL
    update_personal_db(pdb_path, skip_backup=args['--nobackup'])
示例#4
0
def main(wf):
    """Accept Alfred's args and pipe to workflow class"""
    argv = docopt(config.__usage__,
                  argv=wf.args,
                  version=config.__version__)
    log.info(wf.args)
    pd = ZotWorkflow(wf)
    res = pd.run(argv)
    if res:
        print(res)
示例#5
0
def parse(command=None):
    """ Execute the command from user inputs

        It uses 'sys.argv' to take inputs from user
    """

    arguments = docopt(__doc__, version=__version__)

    print(arguments)

    return arguments
示例#6
0
def main(argv):
    """
    Interpret command line arguments and run the corresponding command.
    """
    args = docopt(__doc__, argv=argv, help=True)

    if args['FILE'] is not None:
        addentry(args['FILE'])
    else:
        # TODO: remove after testing code
        raise Exception("Reached the end of command line arg processing"
                        "without doing anything. Code has a logic error.")
示例#7
0
def main(argv):
    """
    Interpret command line arguments and run the corresponding command.
    """
    args = docopt(__doc__, argv=argv, help=True)
    
    if args["check"]:
        check_all()
    elif args["dump"]:
        dump()
    elif args["setdefaults"]:
        set_defaults()
示例#8
0
文件: hkg.py 项目: Eadrom/python-hkg
def parse_args():
    """Parses the command line arguments and parameters provided when hkg is executed

    Args:

    Returns:
         Dictionary containing arguments as keys

    """
    docstring = """HKG - a simple package manager for your home directory

    Usage:
      hkg install <package_name>
      hkg remove <package_name>
      hkg update [--no-preserve] (<package_name> | all)
      hkg info <package_name>
      hkg repo (add | del) <repo_url>
      hkg repo (init | update) <path_to_repo>
      hkg list (repos | packages (<repo_url> | all | local))
      hkg package [init] <path_to_package_tree>
      hkg readme
      hkg (-h | --help)
      hkg --version

    Options:
      -h --help     Show this screen.
      --version     Show version.
    """

    # This bit of code prevents HKG version info to not be hard-coded into the python code and instead use pkg metadata
    # If we don't have a local package database already created, we'll need to make a new default one
    if not os.path.isfile(
            os.path.expanduser('~/.local/share/hkg/packages.hdb')):
        init_package_database(os.path.expanduser('~/.local/share/hkg'))
    # Check if HKG has been installed
    if package_database_api(
            os.path.expanduser('~/.local/share/hkg/packages.hdb'), 'check',
            'INSTALLED', 'hkg', ''):
        # Set version using local package database info
        hkg_version = package_database_api(
            os.path.expanduser('~/.local/share/hkg/packages.hdb'), 'version',
            'INSTALLED', 'hkg', '')
        hkg_version = 'HKG - ' + hkg_version
    else:
        # Tell user they need to install HKG in order for --version to pull
        hkg_version = 'Please install HKG to gain access to version information.'

    #
    return docopt.docopt(docstring, version=hkg_version)
示例#9
0
def main(argv):
    """
    Interpret command line arguments and run the corresponding command.
    """
    args = docopt(__doc__, argv=argv, help=True)

    # ensure that current branch is clean
    if config.unstaged_changes_exist():
        error(messages.UNSTAGED_CHANGES_ERROR)
        exit(1)

    if config.uncommitted_staged_changes_exist():
        error(messages.UNCOMITTED_STAGED_CHANGES_ERROR)
        exit(1)

    if args['master']:
        switch_to_master()
    elif args['dbedit']:
        switch_to_dbedit(do_reset=args["--reset"])
        
    else:
        # TODO: remove after testing code
        raise Exception("Reached the end of command line arg processing "
                        "without doing anything. Code has a logic error.")
示例#10
0
    copy(tmpFile, brightFile)
    os.remove(tmpFile)

def main(arguments):
    if (arguments['-s'] == True):
        # set the value
        print("Setting the value")
        setBrightness(int(float(arguments['<value>'])))
    elif (arguments['-p'] == True):
        # print the brightness
        print(getBrightness())
    elif (arguments['-a'] == True):
        # add to the value
        print("Adding to the value")
        brightness = getBrightness()
        brightness = brightness + int(float(arguments['<value>']))
        setBrightness(brightness)
    elif (arguments['-d'] == True):
        # add to the value
        print("Decrementing from the value")
        brightness = getBrightness()
        brightness = brightness - int(float(arguments['<value>']))
        setBrightness(brightness)
    else:
        # error no option found
        print("Error. Invalid Option! (or lack there of)")

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Brightness 1.0.0') # create the flags from the comment
    main(arguments)
示例#11
0
    keep_days = args.pop('--keep-days')
    cmd, backup_path, backup_base, top_backup_base = build_mydumper(**args)
    #check_space(top_backup_base, keep_days, False)
    succ = run_backup(cmd)
    print('Backup ended {0}'.format(('Error', 'Successfully')[succ]))
    #if succ and args['--compress']:
    #    tar_dir(backup_path)


def create_backup_dir(backup_type, level=None):
    None


if __name__ == '__main__':
    args = docopt(__doc__, version=__version__)
    schema = Schema({
        '<path>': Or(None, And(os.path.exists, error='{0} Not Valid Path'.format(args['<path>']))),
        '--chunk-filesize': Use(int, error='Must be integer with size in MB'),
        '--keep-days': Use(int, error='keep_days must be an integer value'),
        '--threads': Use(int, error='threads must be an integer value'),
        '--updated-since': Or(None, And(Use(int), error='updated since must be integer days')),
        #'--regex': Or(None, And(str, lambda s: re.sub(r'\\|..'
        object: object
        })
    try:
        args = schema.validate(args)
    except SchemaError, e:
        sys.exit(e.code)
    print args
    start = datetime.now()
                add_energy(run_id=run_id, name=name, e=e, err=None, overwrite=self.overwrite)

        conn.commit()

    def add_qmc(self):

        for name, energy, err in self.data_tuple_triple:

            add_energy(run_id=self.run_id, name=name, e=energy, err=err, overwrite=self.overwrite)

        conn.commit()


if __name__ == "__main__":

    arguments = docopt(__doc__)
    v = Vladimir(arguments)

    if arguments["put_in"]:
        if arguments["--simple"]:
            v.add_simple_energy()
        elif arguments["--epp"]:
            v.add_cipsi_epp()
        elif arguments["--cipsi"]:
            v.add_cipsi()
        elif arguments["--qmc"]:
            v.add_qmc()
    elif arguments["remove"]:
        delete_run_id(run_id=arguments["--run"], commit=True)
示例#13
0
文件: conlleva.py 项目: kimgerdes/SUD
		except: pass
		matchingRoots = sg.findall(intree)
		if matchingRoots or includeNonMatchingTrees:
			collectedConll += htmlconll.format(heading=str(i+1), conll=intree.conllu(), stat="")
	
	if collectedConll:
		with open(outhtml,"w") as outf:
			outf.write(htmltemplate.replace("{conll}",collectedConll) )	
		print("written",outhtml)
	else:
		print("no matches found")
		
	
		
if __name__ == "__main__":
	arguments = docopt.docopt(__doc__, version='Conlleva 1.0')
	#print("***",arguments)
	if 	arguments['tohtml']: 		conll2html(arguments['<conllu_file>'])
	elif 	arguments['search']: 		searchConllView(arguments['<conllgrammar_file>'], arguments['<conllu_file>'], includeNonMatchingTrees=arguments['--includeNonMatchingTrees'])
	elif 	arguments['transform']: 	transConllView(arguments['<transconllgrammar_file>'], arguments['<conllu_file>'], addstat=arguments['--addStat'])
	

"""
python3 conlleva.py tohtml "../ud-treebanks-v2.1/UD_French-Sequoia/fr_sequoia-ud-test.conllu"
python3 conlleva.py search search.udauxaux.conllu "../ud-treebanks-v2.1/UD_French-Sequoia/fr_sequoia-ud-test.conllu" -i

python3 conlleva.py transform UDtoSUD.txt "../ud-treebanks-v2.1/UD_French-Sequoia/fr_sequoia-ud-test.conllu" -a
python3 conlleva.py transform UDtoSUD.txt "../ud-treebanks-v2.1/UD_French/fr-ud-dev.conllu" -a
python3 conlleva.py transform UDtoSUD.txt "../ud-treebanks-v2.1/UD_German/de-ud-dev.conllu" -a
python3 conlleva.py transform UDtoSUD.txt "../ud-treebanks-v2.1/UD_English/en-ud-test.conllu" -a
python3 conlleva.py transform UDtoSUD.txt "../ud-treebanks-v2.1/UD_Finnish/fi-ud-test.conllu" -a
示例#14
0
    gui_data["t1 seconds"] = (t1_sec)
    gui_data["t1"] = (t1)
    gui_data["t4 seconds"] = (t4_sec)
    gui_data["t4"] = (t4)

    return gui_data


############################################################################
##
## If run from commandline, we can test the library
##
if __name__ == "__main__":

    arguments = docopt(__doc__, version='Keysight DSO-S 254A version 01')

    tic_file = sys.argv[1]
    if len(sys.argv) == 3 and sys.argv[2] == "tic":
        tic_data = tic.file_to_scipy_array(tic_file)
        num = len(tic_data[0])  # x-axis in [0]
        t_hist = tic_data[1]  # y-axis in [1]
        hist_tic = plt.figure("Time Interval Counter skew")
    elif len(sys.argv) != 4:
        print("### wrong number of input arguments")
        sys.exit()
    else:
        wr_gui_file = sys.argv[2]
        src = sys.argv[3]
        if src == "t1":
            ts_output = "tx_ts"
示例#15
0
        else:
            lst_edge_to_sfd.append(d_edge - d_sfd)

        print("########################")

    edge_to_sfd = scipy.array(lst_edge_to_sfd)
    return (edge_to_sfd, samples, sample_period, first_filename, filename)


############################################################################
##
## If run from commandline, we can test the library
##
if __name__ == "__main__":

    arguments = docopt(__doc__, version='Edge to SFD delay 1.1')

    # defaults:
    DEFAULT_TOL = 1.0e+9

    expect_max_edge = 0
    expect_max_sfd = 0
    estimated_delay = 0.0
    tolerance = DEFAULT_TOL
    bit_width = 20
    time_base = 50.0e-9  # 50 ns/div
    num_meas = 1

    if len(sys.argv) < 10:
        for i in range(1, len(sys.argv)):
            option = sys.argv[i].split('=')
    g09_file_format = ["# cc-pvdz {0}".format(method), 
                        "", line, "",
                       "{0} {1}".format(d_ele["charge"], d_ele["multiplicity"])]

    for atom, xyz in zip(d_ele["formula_flat"], d_ele[geo]):
        line_xyz = "    ".join(map(str, xyz)).replace("e", ".e")
        line = "    ".join([atom, line_xyz])

        g09_file_format.append(line)
    g09_file_format.append("\n\n\n")

    return "\n".join(map(str, g09_file_format))

if __name__ == '__main__':

    arguments = docopt(__doc__, version='G2 Api ' + version)

    if arguments["list_geometries"]:

        if arguments["--ele"]:
            cond = cond_sql_or("ele_tab.name", arguments["--ele"])
            where = "AND".join(cond)
        else:
            where = '(1)'

        r = list_geo(where_cond=where)
        assert r, "No geometries for {0} elements".format(arguments["--ele"])
        print ", ".join(r)

    elif arguments["list_elements"]:
示例#17
0
#!/usr/bin/env python3.7
"""Usage: shapes_and_sound.py [ -h | -help ]

-h --help   A basic child game sowing a shape on every keyboard click.

"""

from lib.docopt import docopt
from src.Game.screen_handler import FullScreenWindow

docopt(__doc__)

if __name__ == '__main__':
    label_timeout = 10000
    max_elements = 10
    w = FullScreenWindow(label_timeout, max_elements)
    w.tk.mainloop()

示例#18
0
        "{0} {1}".format(d_ele["charge"], d_ele["multiplicity"])
    ]

    for atom, xyz in zip(d_ele["formula_flat"], d_ele[geo]):
        line_xyz = "    ".join(map(str, xyz)).replace("e", ".e")
        line = "    ".join([atom, line_xyz])

        g09_file_format.append(line)
    g09_file_format.append("\n\n\n")

    return "\n".join(map(str, g09_file_format))


if __name__ == '__main__':

    arguments = docopt(__doc__, version='G2 Api ' + version)

    if arguments["list_geometries"]:

        if arguments["--ele"]:
            cond = cond_sql_or("ele_tab.name", arguments["--ele"])
            where = "AND".join(cond)
        else:
            where = '(1)'

        r = list_geo(where_cond=where)
        assert r, "No geometries for {0} elements".format(arguments["--ele"])
        print ", ".join(r)

    elif arguments["list_elements"]:
示例#19
0
                           [--order_by=<column>...]
                           [--ref=<id>]

Options:
  --ref=<id>    Speed in knots [default: 66474780].

"""
#
# |  o |_  ._ _. ._
# |_ | |_) | (_| | \/
#                  /
from lib.docopt import docopt
from src.calc import BigData
from src.print_util import print_mad_recap

#
# |\/|  _. o ._
# |  | (_| | | |
#
if __name__ == '__main__':

    d_arguments = docopt(__doc__)
    q = BigData(d_arguments=d_arguments)

    if d_arguments["--order_by"]:
        order_by = d_arguments["--order_by"]
    else:
        order_by = ["mad"]

    print_mad_recap(q, order_by=order_by)
示例#20
0
            search_string = get_search_string()
        else:
            choice = True
    stations_only = "True"
    max_results = "10"

    url = "http://endemoniada.org/trafiklab.php?api=typeahead" + \
        "&searchstring=" + quote(search_string) + \
        "&stationsonly=" + stations_only + \
        "&maxresults=" + max_results
    stream = urlopen(url)
    data = json.load(stream)

    if data['StatusCode'] != 0:
        print "StatusCode: %s\nMessage: %s" % (
            data['StatusCode'], data['Message']
        )
    else:
        choice = print_search_results(data['ResponseData'], choice)

    if choice:
        return choice

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Pendla v1.3.0')
    try:
        main(arguments)
    except KeyboardInterrupt:
        print "\nExiting..."
    exit()