def test_verbose_and_version(): doc = '''Usage: test.py [options] Options: -v, --verbose Not silent. ''' parser = argopt(doc, version='4.3.2-1.0') fs = StringIO() parser.print_help(file=fs) res = fs.getvalue() try: assert (i in res for i in '''usage: test.py [-h] [-v] [--version] optional arguments: -h, --help show this help message and exit -v, --verbose Not silent. --version, --version show program's version number and exit '''.split('\n')) except AssertionError: raise AssertionError(res) args = parser.parse_args(args=['-v']) assert args.verbose args = parser.parse_args(args=[]) assert (not args.verbose) try: parser.parse_args(args=['--version']) except SystemExit as e: assert (str(e) == '0') else: raise ValueError('System should have exited with code 0')
def test_basic(): doc = ''' Example programme description. You should be able to do args = argopt(__doc__).parse_args() instead of args = docopt(__doc__) Usage: test.py [-h | options] <x> Y [<z>...] Arguments: <x> A file. --anarg=<a> Description here [default: 1e3:int]. -p PAT, --patts PAT Or [default: '':str]. --bar=<b> Another [default: something] should assume str. -f, --force Force. ''' parser = argopt(doc, version='0.1.2-3.4', formatter_class=RawDescriptionHelpFormatter) fs = StringIO() parser.print_help(file=fs) res = fs.getvalue() try: assert ('''Example programme description. You should be able to do args = argopt(__doc__).parse_args() instead of args = docopt(__doc__)''' in res) assert (i in res for i in '''positional arguments: x A file. Y z optional arguments: -h, --help show this help message and exit --bar b Another [default: something] should assume str. -v, --version show program's version number and exit -f, --force Force. --anarg a Description here [default: 1e3:int]. -p PAT, --patts PAT Or [default: '':str].'''.split('\n')) except AssertionError: # if not all([l.strip() in res for l in doc.split('\n')]): raise AssertionError(res) args = parser.parse_args(args='such test much is'.split()) try: assert (args.x == 'such') except AssertionError as e: raise AssertionError("x:" + str(args.x) + str(e)) assert (args.Y == 'test') assert (args.z == 'much is'.split()) try: parser.parse_args(args=['-v']) except SystemExit as e: assert (str(e) == '0') else: raise ValueError('System should have exited with code 0')
def main(argv=None): """argv : list, optional (default: sys.argv[1:])""" args = argopt(__doc__ % (__version__, __author__), version=__version__).parse_args(args=argv) logging.basicConfig(level=getattr(logging, args.log, logging.INFO)) log.debug(args) return run(args) or 0
def main(args=None): """args : list [default: sys.argv[1:]]""" from argopt import argopt args = argopt(__doc__ + '\n' + __copyright__, version=__version__).parse_args(args=args) logging.basicConfig( level=getattr(logging, args.log, logging.INFO), stream=TqdmStream, format="%(levelname)s:gitfame.%(funcName)s:%(lineno)d:%(message)s") log = logging.getLogger(__name__) log.debug(args) if args.manpath is not None: from os import path from shutil import copyfile from pkg_resources import resource_filename, Requirement import sys fi = resource_filename(Requirement.parse('git-fame'), 'gitfame/git-fame.1') fo = path.join(args.manpath, 'git-fame.1') copyfile(fi, fo) log.info("written:" + fo) sys.exit(0) run(args)
def main(argv=None): logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(funcName)s:%(message)s") args = argopt(__doc__).parse_args(argv) ensure_spm(cache=args.cache, version=args.spm_version) print("SPM{v} is successfully installed".format(v=args.spm_version)) return 0
def main(doc): parser = argopt(doc, version='0.1.2-3.4') # parser.print_help() # parser = argopt(doc, argparser=GooeyParser) args = parser.parse_args() print (args)
def main(argv=None): """argv : list, optional (default: sys.argv[1:])""" args = argopt(__doc__, version=__version__).parse_args(args=argv) logging.basicConfig( level=getattr(logging, args.log, logging.INFO), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s") log = logging.getLogger(__name__) log.debug(args) return run(args) or 0
def test_basic(): doc = ''' Example programme description. You should be able to do args = argopt(__doc__).parse_args() instead of args = docopt(__doc__) Usage: test.py [-h | options] <x> [<y>...] Arguments: <x> A file. --anarg=<a> Description here [default: 1e3:int]. -p PAT, --patts PAT Or [default: '':str]. --bar=<b> Another [default: something] should assume str. -f, --force Force. -v, --version Print version and exit. ''' parser = argopt(doc, version='0.1.2-3.4', formatter_class=argparse.RawDescriptionHelpFormatter) fs = StringIO() parser.print_help(file=fs) res = fs.getvalue() try: assert ('''Example programme description. You should be able to do args = argopt(__doc__).parse_args() instead of args = docopt(__doc__)''' in res) assert (i in res for i in '''positional arguments: x A file. y optional arguments: -h, --help show this help message and exit --bar b Another [default: something] should assume str. -v, --version show program's version number and exit -f, --force Force. --anarg a Description here [default: 1e3:int]. -p PAT, --patts PAT Or [default: '':str].'''.split('\n')) except AssertionError: raise AssertionError(res) args = parser.parse_args(args=' such test much is'.split()) assert (args.x == 'such') assert (args.x == 'such') assert (args.y == 'test much is'.split())
def main(): args = argopt(__doc__, version=__version__).parse_args() logging.basicConfig(level=getattr(logging, args.log, logging.INFO)) xml = None with open(XML_FILE) as fp: xml = fp.read() jdict = None with open(args.in_json_file) as fp: jdict = flatDict(json.load(fp)) for (k, v) in jdict.items(): xml = xml.replace("{{" + k + "}}", v) with open(args.out_xml_file, 'wb') as fp: fp.write(xml)
def main(): try: parser = argopt(__doc__, argparser=CustomParser, conflict_handler='resolve', version='0.1.2-3.4', epilog='That was fun!') except IOError as e: if "demo_advanced.py" in str(e): # Our docstring insists on a default file argument "demo_basic.py" # in the current working directory. raise EnvironmentError( 'Please change to directory "%s" where "demo_basic.py" exists' ' before re-running "%s"' % (os.path.dirname(__file__), __file__)) raise args = parser.parse_args() print (args)
def main(): try: parser = argopt(__doc__, argparser=CustomParser, conflict_handler='resolve', version='0.1.2-3.4', epilog='That was fun!') except IOError as e: if "demo_advanced.py" in str(e): # Our docstring insists on a default file argument "demo_basic.py" # in the current working directory. raise EnvironmentError( 'Please change to directory "%s" where "demo_basic.py" exists' ' before re-running "%s"' % (os.path.dirname(__file__), __file__)) raise args = parser.parse_args() print(args)
def __init__( self, func, doc, version=None, argparser=MyParser, formatter_class=RawDescriptionHelpFormatter, **kwargs, ): """ Args: func (callable): e.g. `os.path.isdir` doc (str): an `argopt`-compatible docstring for `func` version (str): optional """ super(Func, self).__init__(**kwargs) self.parser = argopt( dedent(doc), argparser=argparser, formatter_class=formatter_class, version=version, ) self.parser.set_defaults(run__=func)
def __init__( self, cmd, doc, version=None, argparser=MyParser, formatter_class=RawDescriptionHelpFormatter, **kwargs, ): """ Args: cmd (list): e.g. `[sys.executable, "-m", "miutil.cuinfo"]` doc (str): an `argopt`-compatible docstring for `cmd` version (str): optional """ super(Cmd, self).__init__(**kwargs) self.parser = argopt( dedent(doc), argparser=argparser, formatter_class=formatter_class, version=version, ) self.parser.set_defaults(main__=self.main) self.cmd = cmd
args = argopt(__doc__).parse_args() instead of args = docopt(__doc__) Usage: test.py [options] <x> [<y>...] Arguments: <x> A file. --anarg=<a> Description here [default: 1e3:int]. -p PAT, --patts PAT Or [default: None:file]. --bar=<b> Another [default: something] should auto-wrap something in quotes and assume str. -f, --force Force. """ from argopt import argopt __version__ = "0.1.2-3.4" # parser = argopt(__doc__, version=__version__) # parser.print_help() # args = parser.parse_args() args = argopt(__doc__, version=__version__).parse_args() if args.force: print(args) else: print(args.x)
Usage: greeter [options] [<you>] [<me>] Options: -g, --goodbye : Say "goodbye" (instead of "hello") -b, --print-bash-completion : Output a bash tab-completion script -z, --print-zsh-completion : Output a zsh tab-completion script Arguments: <you> : Your name [default: Anon] <me> : My name [default: Casper] """ import sys, argopt, shtab parser = argopt.argopt(__doc__) def main(): args = parser.parse_args() if args.print_bash_completion: print(shtab.complete(parser, shell="bash")) sys.exit(0) if args.print_zsh_completion: print(shtab.complete(parser, shell="zsh")) sys.exit(0) msg = "k thx bai!" if args.goodbye else "hai!" print("{} says '{}' to {}".format(args.me, msg, args.you))
def main(): args = argopt(__doc__).parse_args() logging.basicConfig(level=getattr(logging, args.log, logging.INFO)) log = logging.getLogger(__name__) log.debug(args) return run(args) or 0
def get_main_parser(): from argopt import argopt return argopt(__doc__ + '\n' + __copyright__, version=__version__)
def main(): args = argopt(__doc__, version=__version__).parse_args() if args.debug_brace: args.debug = "NOTSET" logging.basicConfig(level=getattr(logging, args.debug, logging.INFO), format='%(levelname)s:%(message)s') log = logging.getLogger(__name__) log.debug(args) # Get compressed sizes zips = {} for fn in args.zipfiles: info = subprocess.check_output(["7z", "l", fn]).strip() finfo = RE_SCN.findall(info) # size|compressed|name # builtin test: last line should be total sizes log.debug(finfo) totals = map(int, finfo[-1][:2]) # log.debug(totals) for s in range(2): # size|compressed totals totals_s = sum(map(int, (inf[s] for inf in finfo[:-1]))) if totals_s != totals[s]: log.warn("%s: individual total %d != 7z total %d" % (fn, totals_s, totals[s])) fcomp = dict( (n, int(c if args.compressed else u)) for (u, c, n) in finfo[:-1]) # log.debug(fcomp) # zips : {'zipname' : {'filename' : int(size)}} zips[fn] = fcomp # Exbract cmd7zx = ["7z", "x", "-bd"] if args.yes: cmd7zx += ["-y"] log.info("Exbracting from {:d} file(s)".format(len(zips))) with tqdm(total=sum(sum(fcomp.values()) for fcomp in zips.values()), unit="B", unit_scale=True) as tall: for fn, fcomp in zips.items(): md, sd = pty.openpty() ex = subprocess.Popen( cmd7zx + [fn], bufsize=1, stdout=md, # subprocess.PIPE, stderr=subprocess.STDOUT) os.close(sd) with io.open(md, mode="rU", buffering=1) as m: with tqdm(total=sum(fcomp.values()), disable=len(zips) < 2, leave=False, unit="B", unit_scale=True) as t: if not hasattr(t, "start_t"): # disabled t.start_t = tall._time() while True: try: l_raw = m.readline() except IOError: break ln = l_raw.strip() if ln.startswith("Exbracting"): exname = ln.lstrip("Exbracting").lstrip() s = fcomp.get(exname, 0) # 0 is likely folders t.update(s) tall.update(s) elif ln: if not any( ln.startswith(i) for i in ("7-Zip ", "p7zip Version ", "Everything is Ok", "Folders: ", "Files: ", "Size: ", "Compressed: ")): if ln.startswith("Processing archive: "): if not args.silent: t.write( t.format_interval(t.start_t - tall.start_t) + ' ' + ln.lstrip("Processing archive: ")) else: t.write(ln) ex.wait()
def main(): args = argopt(__doc__, version=__version__).parse_args() if args.debug_trace: args.debug = "NOTSET" logging.basicConfig(level=getattr(logging, args.debug, logging.INFO), format='%(levelname)s:%(message)s') log = logging.getLogger(__name__) log.debug(args) # Get compressed sizes zips = {} for fn in args.zipfiles: info = subprocess.check_output(["7z", "l", fn]).strip() finfo = RE_SCN.findall(info) # size|compressed|name # builtin test: last line should be total sizes log.debug(finfo) totals = map(int, finfo[-1][:2]) # log.debug(totals) for s in range(2): # size|compressed totals totals_s = sum(map(int, (inf[s] for inf in finfo[:-1]))) if totals_s != totals[s]: log.warn("%s: individual total %d != 7z total %d" % ( fn, totals_s, totals[s])) fcomp = dict((n, int(c if args.compressed else u)) for (u, c, n) in finfo[:-1]) # log.debug(fcomp) # zips : {'zipname' : {'filename' : int(size)}} zips[fn] = fcomp # Extract cmd7zx = ["7z", "x", "-bd"] if args.yes: cmd7zx += ["-y"] log.info("Extracting from {:d} file(s)".format(len(zips))) with tqdm(total=sum(sum(fcomp.values()) for fcomp in zips.values()), unit="B", unit_scale=True) as tall: for fn, fcomp in zips.items(): md, sd = pty.openpty() ex = subprocess.Popen( cmd7zx + [fn], bufsize=1, stdout=md, # subprocess.PIPE, stderr=subprocess.STDOUT) os.close(sd) with io.open(md, mode="rU", buffering=1) as m: with tqdm(total=sum(fcomp.values()), disable=len(zips) < 2, leave=False, unit="B", unit_scale=True) as t: if not hasattr(t, "start_t"): # disabled t.start_t = tall._time() while True: try: l_raw = m.readline() except IOError: break ln = l_raw.strip() if ln.startswith("Extracting"): exname = ln.lstrip("Extracting").lstrip() s = fcomp.get(exname, 0) # 0 is likely folders t.update(s) tall.update(s) elif ln: if not any( ln.startswith(i) for i in ("7-Zip ", "p7zip Version ", "Everything is Ok", "Folders: ", "Files: ", "Size: ", "Compressed: ")): if ln.startswith("Processing archive: "): if not args.silent: t.write(t.format_interval( t.start_t - tall.start_t) + ' ' + ln.lstrip("Processing archive: ")) else: t.write(ln) ex.wait()
if tag in seq[i - 1]: seq[i] = f"I-{tag}" continue seq[i] = f"B-{tag}" return new_tags def run(annotation_xml_path): logging.info(f"Treating file {annotation_xml_path}") tqdm.write(f"Treating file {annotation_xml_path}") return 1, annotation_xml_path if __name__ == '__main__': parser = argopt(__doc__).parse_args() tagged_file_path = parser.docs_folder n_jobs = parser.cores annotated_txt_paths = glob.glob(tagged_file_path + "**/*.txt", recursive=True) if n_jobs < 2: job_output = [] for annotation_xml_path in tqdm(annotated_txt_paths): job_output.append(run(annotation_xml_path)) else: job_output = Parallel(n_jobs=n_jobs)( delayed(run)(annotation_xml_path) for annotation_xml_path in tqdm(annotated_txt_paths)) # Get correctly processed paths