def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) parser.usage = "python -m " + parser.format_usage().split(':')[1].strip() return parser
def _get_parser(): """ Returns a parser to handle command line args. """ parser = ArgumentParser() parser.usage = "benchmark [options]" parser.add_argument('projects', metavar='project', nargs='*', help='project to benchmark (references a JSON file in the working directory)') parser.add_argument('-f', '--force', action='store_true', dest='force', help='do the benchmark even if nothing has changed') parser.add_argument('-u', '--unit-tests', action='store_true', dest='unit_tests', help='run the unit tests before running the benchmarks.') parser.add_argument('-k', '--keep-env', action='store_true', dest='keep_env', help='keep the created conda env after execution (usually for troubleshooting purposes)') parser.add_argument('-p', '--plot', metavar='SPEC', action='store', dest='plot', help='plot benchmark history for SPEC') parser.add_argument('-c', '--check', action='store_true', dest='check', help='check the most recent benchmark data for >10%% change') parser.add_argument('-d', '--dump', action='store_true', dest='dump', help='dump the contents of the database to an SQL file') return parser
def _configure_arg_parser(): parser = ArgumentParser(prog='ties-validate', formatter_class=RawDescriptionHelpFormatter) parser.usage = 'ties-validate [-h] [--version] [FILE]...' parser.description = 'Validate FILE(s), or standard input, against the TIES 0.9 schema.' parser.epilog = ('''\ If FILE arguments are provided, attempts to validate all files. FILE arguments may be provided as either file paths or shell globs. If no FILE arguments are provided, attempts to read a single JSON object from stdin and validate it. Returns non-zero exit code if one or more input files fail to validate successfully. ''') parser.add_argument( 'files', metavar='FILE', nargs='*', help= 'the path to the JSON file(s) to be validated against the schema or - to read from stdin' ) parser.add_argument('--version', action=VersionAction, version="TIES Schema Validator\n{}".format( version_string()), help='prints version information') return parser
def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) root_help_dict = {"curdir": os.curdir, "cwd": os.getcwd()} parser.add_argument( "root", type=_directory, help=( "The directory to begin test discovery. Use '{curdir}' " + "for the current working directory: {cwd}" ).format(**root_help_dict), ) parser.add_argument( "-p", "--pattern", default=".*", type=_regex, help="Only modules whose name fits this pattern will be " + "searched. (default: %(default)s)", ) main.compose(parser) parser.usage = "python -m " + parser.format_usage().split(":")[1].strip() return parser
def create_argument_parser(): """Create the argument parser.""" parser = ArgumentParser(add_help=False) parser.usage = "gcovr [options] [search_paths...]" parser.description = \ "A utility to run gcov and summarize the coverage in simple reports." parser.epilog = "See <http://gcovr.com/> for the full manual." options = parser.add_argument_group('Options') options.add_argument( "-h", "--help", help="Show this help message, then exit.", action="help" ) options.add_argument( "--version", help="Print the version number, then exit.", action="store_true", dest="version", default=False ) argument_parser_setup(parser, options) return parser
def _get_parser(): """ Returns a parser to handle command line args. """ parser = ArgumentParser() parser.usage = "benchmark [options]" parser.add_argument( 'projects', metavar='project', nargs='*', help= 'project to benchmark (references a JSON file in the working directory)' ) parser.add_argument('-f', '--force', action='store_true', dest='force', help='do the benchmark even if nothing has changed') parser.add_argument( '-u', '--unit-tests', action='store_true', dest='unit_tests', help='run the unit tests before running the benchmarks.') parser.add_argument( '-k', '--keep-env', action='store_true', dest='keep_env', help= 'keep the created conda env after execution (usually for troubleshooting purposes)' ) parser.add_argument('-p', '--plot', metavar='SPEC', action='store', dest='plot', help='plot benchmark history for SPEC') parser.add_argument( '-c', '--check', action='store_true', dest='check', help='check the most recent benchmark data for >10%% change') parser.add_argument( '-d', '--dump', action='store_true', dest='dump', help='dump the contents of the database to an SQL file') return parser
def get_parser(self): p = ArgumentParser(self.description) p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument( '-f', '--force', action='store_true', default=False, help='Force uploading even if it overwrites an existing image') p.add_argument('--gzip', action='store_true', default=False, help='Upload the image compressed with gzip.') p.add_argument('--resize', type=int, default=0, help='create an image with a new size (in MB)') p.add_argument('--verbose', action='store_true', default=False, help='display verbose output during snapshot') p.add_argument( '--clean', action='store_true', default=False, help= 'Remove any existing local snapshots before creating a new one.') return p
def create_argument_parser(): """Create the argument parser.""" parser = ArgumentParser(add_help=False) parser.usage = "gcovr [options] [search_paths...]" parser.description = ( "A utility to run gcov and summarize the coverage in simple reports.") parser.epilog = "See <http://gcovr.com/> for the full manual." options = parser.add_argument_group("Options") options.add_argument("-h", "--help", help="Show this help message, then exit.", action="help") options.add_argument( "--version", help="Print the version number, then exit.", action="store_true", dest="version", default=False, ) argument_parser_setup(parser, options) return parser
def configure_parser(parser: ArgumentParser, add_usage: bool = True) -> None: """ Add dazl configuration options to an existing :class:`ArgumentParser`. dazl exposes a variety of configuration options that could be tedious to duplicate in your own application. To use this in your own application: .. code-block:: python parser = argparse.ArgumentParser(description='Something awesome with dazl.') configure_parser(parser) args = parser.parse_args() conn = dazl.connect(**args) :param parser: The :class:`ArgumentParser` to add options to. :param add_usage: ``True`` to overwrite the usage string with something more compact; because there are a lot of variables, the default usage string doesn't add much """ if add_usage: parser.usage = "%(prog)s [OPTIONS]\n\n" + EXAMPLES _configure_url_basic_options(parser) _configure_access(parser) _configure_url_advanced_options(parser) _configure_deprecated_options(parser)
def install_command_parser(**kwargs): global _parser _parser = ArgumentParser(**kwargs) command_parsers_help = "Specify a command to the PyInq package." command_parsers = _parser.add_subparsers(help=command_parsers_help) _install_discovery_parser(command_parsers) _parser.usage = "python -m " + _parser.format_usage().split(':')[1].strip()
def install_command_parser(**kwargs): global _parser _parser = ArgumentParser(**kwargs) command_parsers_help = "Specify a command to the PyInq package." command_parsers = _parser.add_subparsers(help=command_parsers_help) _install_discovery_parser(command_parsers) _install_test_parser(command_parsers) _parser.usage = "python -m " + _parser.format_usage().split(':')[1].strip()
def main(): parser = ArgumentParser() parser.add_argument('mpd') parser.add_argument('files_and_langs', nargs='+', help='List of file language pairs') args = parser.parse_args() if len(args.files_and_langs) % 2 != 0: print("You must list pairs of files and languages") parser.usage() sys.exit(1) subfiles = [] for i in range(len(args.files_and_langs) // 2): subfile = args.files_and_langs[2 * i] lang = args.files_and_langs[2 * i + 1] subfiles.append(SubtitleFile(subfile, lang)) add_subtitles(args.mpd, subfiles)
def configure(self, parser: ArgumentParser): super().configure(parser) parser.add_argument('-i', '--interactive', action='store_true', help='Pass STDIN to the container') parser.add_argument('-t', '--tty', action='store_true', help='Allocate a pseudo-TTY') parser.add_argument('-u', '--user', type=str, default=None, help='Container username or UID (format: <name|uid>[:<group|gid>])') parser.add_argument('--no-sync', action='store_true', help='Don\'t sync the project before running the script') # add the "double-dash" argument to the usage message parser.prog = 'spotty exec' parser.usage = parser.format_usage()[7:-1] + ' -- COMMAND [args...]\n' parser.epilog = 'The double dash (--) separates the command that you want to execute inside the container ' \ 'from the Spotty arguments.'
def format_usage(parser: ArgumentParser, depth: int, invalid_args=None) -> None: usage = parser.format_usage() args = list( filter(lambda arg: arg != "-h" and arg != "--help", sys.argv[:depth])) args[0] = parser.prog if invalid_args: invalid_args = " ".join(invalid_args) if invalid_args in args: args.remove(invalid_args) nusg = " ".join(args) parser.usage = usage.replace(f"Usage: {parser.prog}", nusg, 1)
def get_parser(self): p = ArgumentParser(self.description) p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument( "-f", "--force", action="store_true", default=False, help="Force uploading even if it overwrites an existing image", ) p.add_argument("--gzip", action="store_true", default=False, help="Upload the image compressed with gzip.") p.add_argument("--resize", help="create an image with a new size (in MB)") return p
def get_parser(self): p = ArgumentParser(self.description) p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument('-f', '--force', action='store_true', default=False, help='Force uploading even if it overwrites an existing image') p.add_argument('--gzip', action='store_true', default=False, help='Upload the image compressed with gzip.') p.add_argument('--resize', type=int, default=0, help='create an image with a new size (in MB)') p.add_argument('--verbose', action='store_true', default=False, help='display verbose output during snapshot') p.add_argument('--clean', action='store_true', default=False, help='Remove any existing local snapshots before creating a new one.') return p
def _get_parser(): """ Returns a parser to handle command line args. """ parser = ArgumentParser() parser.usage = "benchmark [options]" parser.add_argument( "projects", metavar="project", nargs="*", help="project to benchmark (references a JSON file in the working directory)", ) parser.add_argument( "-f", "--force", action="store_true", dest="force", help="do the benchmark even if nothing has changed" ) parser.add_argument( "-u", "--unit-tests", action="store_true", dest="unit_tests", help="run the unit tests before running the benchmarks.", ) parser.add_argument( "-k", "--keep-env", action="store_true", dest="keep_env", help="keep the created conda env after execution (usually for troubleshooting purposes)", ) parser.add_argument( "-p", "--plot", metavar="SPEC", action="store", dest="plot", help="plot benchmark history for SPEC" ) parser.add_argument( "-c", "--check", action="store_true", dest="check", help="check the most recent benchmark data for >10%% change" ) parser.add_argument( "-d", "--dump", action="store_true", dest="dump", help="dump the contents of the database to an SQL file" ) return parser
def get_parser(self): p = ArgumentParser(self.description) p.usage = "save name [-h] [-f] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument( '-f', '--force', action='store_true', default=False, help='Force uploading even if it overwrites an existing image') p.add_argument('--gzip', action='store_true', default=False, help='Upload the image compressed with gzip.') p.add_argument('--resize', help='create an image with a new size (in MB)') return p
def compose(parser=None, **kwargs): if not parser: parser = ArgumentParser(**kwargs) root_help_dict = {"curdir": os.curdir, "cwd": os.getcwd()} parser.add_argument("root",type=_directory, help=("The directory to begin test discovery. Use '{curdir}' " + \ "for the current working directory: {cwd}").format(**root_help_dict)) parser.add_argument("-p","--pattern",default=".*",type=_regex, help="Only modules whose name fits this pattern will be " + \ "searched. (default: %(default)s)") main.compose(parser) parser.usage = "python -m " + parser.format_usage().split(':')[1].strip() return parser
def configure(self, parser: ArgumentParser): super().configure(parser) parser.add_argument('script_name', metavar='SCRIPT_NAME', type=str, help='Script name') parser.add_argument( '-u', '--user', type=str, default=None, help='Container username or UID (format: <name|uid>[:<group|gid>])' ) parser.add_argument('-s', '--session-name', type=str, default=None, help='tmux session name') parser.add_argument('-l', '--logging', action='store_true', help='Log the script outputs to a file') parser.add_argument( '-p', '--parameter', metavar='PARAMETER=VALUE', action='append', type=str, default=[], help= 'Set a value for the script parameter (format: PARAMETER=VALUE). This ' 'argument can be used multiple times to set several parameters. Parameters can be ' 'used in the script as Mustache variables (for example: {{PARAMETER}}).' ) parser.add_argument( '--no-sync', action='store_true', help='Don\'t sync the project before running the script') # add the "double-dash" argument to the usage message parser.prog = 'spotty run' parser.usage = parser.format_usage()[7:-1] + ' [-- args...]\n' parser.epilog = 'The double dash (--) separates custom arguments that you can pass to the script ' \ 'from the Spotty arguments.'
def ParseArgs(): """ Function get and parse command line keys. """ parser = ArgumentParser() # command-line string parser parser.description = "Metatrader 4 forex history parser. Read, parse and save history as .csv-file or pandas dataframe. Also you can draw an interactive chart. See examples: https://tim55667757.github.io/MT4ForexParser" parser.usage = "mt4forexparser [some options] [one command]" # options: parser.add_argument("--mt4-history", type=str, required=True, help="Option (required): full path to Metatrader 4 forex history file.") parser.add_argument("--output", type=str, default=None, help="Option: full path to .csv output file. Default is None, mean that returns only pandas dataframe.") parser.add_argument("--debug-level", type=int, default=20, help="Option: showing STDOUT messages of minimal debug level, e.g. 10 = DEBUG, 20 = INFO, 30 = WARNING, 40 = ERROR, 50 = CRITICAL.") # commands: parser.add_argument("--parse", action="store_true", help="Command: read, parse and save mt4-history as pandas dataframe or .csv-file if --output is define.") parser.add_argument("--render", action="store_true", help="Command: use PriceGenerator module to render interactive chart from parsed data. This key only used with --parse key.") cmdArgs = parser.parse_args() return cmdArgs
def get_parser(): parser = ArgumentParser() parser.usage = '%(prog)s function_name [-despachrq]' parser.add_argument('-c', '--color', action='store_true', default=False, help='show matched words in color') parser.add_argument('-s', '--sensitive', action='store_true', default=False, help='be case sensitive') parser.add_argument('-a', '--sum_all_matches', action='store_true', default=False, help='show summary of the results') parser.add_argument('-q', '--quite', action='store_true', default=False, help='show summary of the results') parser.add_argument('-p', '--path', type=str, default='.', help='path to check to start recursive check from') parser.add_argument('-e', '--extensions', type=str, default='txt,robot,py', help='which file extensions to check') parser.add_argument('-d', '--debug', action='store_true', default=False, help='show exception in case of fail') parser.add_argument('-r', '--regex', action='store_true', default=False, help='use regex pattern search') return parser
def nestify_cli(): """Use nestify_json in cli mode""" parser = ArgumentParser() parser.usage = USAGE_MESSAGE _add_params(parser) args = parser.parse_args() if args.debug: _logger.setLevel(logging.getLevelName(args.debug.upper())) _logger.debug('Debug mode: ON') _logger.debug(args) file = getattr(args, 'file', None) if not file and sys.stdin.isatty(): parser.print_help() exit(2) _fileinput = fileinput.input(file or ('-',)) try: _input = json.loads(''.join(_fileinput)) except (ValueError, json.JSONDecodeError, TypeError) as e: _logger.debug(f'INPUT: {"".join(_fileinput)}') _logger.debug(e) sys.stderr.write(f'Could not parse JSON\n') else: _logger.debug(f'INPUT LENGTH: {len(_input)}') try: nested = nestify(_input, *args.group) except Exception as e: _logger.error(e) sys.stderr.write(f'Could not create nested dictionary\n') else: _logger.debug(f'OUTPUT LENGTH: {len(nested)}') sys.stdout.write(f'{nested}\n')
import xml.parsers.expat p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.ParseFile(open(fn)) if __name__ == "__main__": from argparse import ArgumentParser global args parser = ArgumentParser() parser.usage = """ prog [args] file1 [file2...] --- hash files and produce DFXML [args] dir1 [dir2...] --- hash dirs and produce DFXML You can also extract a set of hashes to stdout with: [--md5 | --sha1 | --sha256] --extract=filename.xml Note: MD5 output is assumed unless another hash algorithm is specified. """ parser.add_argument("--piecewise", help="Specifies size of piecewise hashes", default=0, type=int) parser.add_argument("--addfixml", help="Specifies XML to add to each file object (for labeling)") parser.add_argument("--sha1", help="Generate sha1 hashes", action="store_true") parser.add_argument("--md5", help="Generate MD5 hashes", action="store_true") parser.add_argument("--sha256", help="Generate sha256 hashes", action="store_true") parser.add_argument("--output", help="Specify output filename (default stdout)") parser.add_argument("--extract", help="Specify a DFXML to extract a hash set from")
import importlib.util import logging import os import sys from argparse import ArgumentParser logger = logging.getLogger('merger') if __name__ == '__main__': parser = ArgumentParser() parser.usage = "Merge and remap multiple csv files" parser.add_argument('path', help='Path to data folder') parser.add_argument('--output', help='Set merge result output', choices=['csv']) parser.add_argument('--debug', help='Set debug mode', action="store_true") parser.add_argument('--settings', help='Provide custom settings python module path') args = parser.parse_args() logger.debug(f'settings {args.settings} imported') if args.settings: spec = importlib.util.spec_from_file_location("settings", args.settings) settings = importlib.util.module_from_spec(spec) sys.modules['settings'] = settings spec.loader.exec_module(settings)
if __name__ == "__main__": # I like colors :-) RESET = "\x1B[0m" RED = "\x1B[31m" GREEN = "\x1B[32m" BLUE = "\x1B[34m" parser = ArgumentParser(description=__desc__, epilog="\t---[ EOT ]---", prog=__file__) parser.usage = """{0} [--type {4}format{2}] [options*] {3}nmap.xml{2} [nmap.xml ...] \twhere {3}nmap.xml{2} is the XML file provided by nmap -oA/-oX option \tand {4}format{2} is in {1} """.format(__file__, '/'.join(SUPPORTED_FORMATS.keys()), RESET, BLUE, GREEN ) parser.add_argument("filelist", type=str, metavar="nmap.xml[,nmap.xml]*", nargs='*', help="specify path to XML Nmap file(s)",) parser.add_argument("-v", "--verbose", action="count", dest="verbose", help="increments verbosity") parser.add_argument("--version", action="version", version=__version__) parser.add_argument("-t", "--type", type=str, metavar="TYPE", dest="type", help="specify output format output. "+ "Supported formats are: "+'/'.join(SUPPORTED_FORMATS.keys()), choices = SUPPORTED_FORMATS.keys(), default="txt")
def _get_parser(): """Returns a parser to handle command line args.""" parser = ArgumentParser() parser.usage = "testflo [options]" parser.add_argument('-c', '--config', action='store', dest='cfg', metavar='FILE', help='Path of config file where preferences are specified.') parser.add_argument('-t', '--testfile', action='store', dest='testfile', metavar='FILE', help='Path to a file containing one testspec per line.') parser.add_argument('--maxtime', action='store', dest='maxtime', metavar='TIME_LIMIT', default=-1, type=float, help='Specifies a time limit in seconds for tests to be saved to ' 'the quicktests.in file.') try: cpus = cpu_count() except: warnings.warn('CPU count could not be determined. Defaulting to 1') cpus = 1 parser.add_argument('-n', '--numprocs', type=int, action='store', dest='num_procs', metavar='NUM_PROCS', default=cpus, help='Number of processes to run. By default, this will ' 'use the number of CPUs available. To force serial' ' execution, specify a value of 1.') parser.add_argument('-o', '--outfile', action='store', dest='outfile', metavar='FILE', default='testflo_report.out', help='Name of test report file. Default is testflo_report.out.') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help="Include testspec and elapsed time in " "screen output. Also shows all stderr output, even if test doesn't fail") parser.add_argument('--compact', action='store_true', dest='compact', help="Limit output to a single character for each test.") parser.add_argument('--dryrun', action='store_true', dest='dryrun', help="Don't actually run tests, but print " "which tests would have been run.") parser.add_argument('--pre_announce', action='store_true', dest='pre_announce', help="Announce the name of each test before it runs. This " "can help track down a hanging test. This automatically sets -n 1.") parser.add_argument('-f', '--fail', action='store_true', dest='save_fails', help="Save failed tests to failtests.in file.") parser.add_argument('-i', '--isolated', action='store_true', dest='isolated', help="Run each test in a separate subprocess.") parser.add_argument('--nompi', action='store_true', dest='nompi', help="Force all tests to run without MPI. This can be useful " "for debugging.") parser.add_argument('-x', '--stop', action='store_true', dest='stop', help="Stop after the first test failure, or as soon as possible" " when running concurrent tests.") parser.add_argument('-s', '--nocapture', action='store_true', dest='nocapture', help="Standard output (stdout) will not be captured and will be" " written to the screen immediately.") parser.add_argument('--coverage', action='store_true', dest='coverage', help="Perform coverage analysis and display results on stdout") parser.add_argument('--coverage-html', action='store_true', dest='coveragehtml', help="Perform coverage analysis and display results in browser") parser.add_argument('--coverpkg', action='append', dest='coverpkgs', metavar='PKG', help="Add the given package to the coverage list. You" " can use this option multiple times to cover" " multiple packages.") parser.add_argument('--cover-omit', action='append', dest='cover_omits', metavar='FILE', help="Add a file name pattern to remove it from coverage.") parser.add_argument('-b', '--benchmark', action='store_true', dest='benchmark', help='Specifies that benchmarks are to be run rather ' 'than tests, so only files starting with "benchmark_" ' 'will be executed.') parser.add_argument('-d', '--datafile', action='store', dest='benchmarkfile', metavar='FILE', default='benchmark_data.csv', help='Name of benchmark data file. Default is benchmark_data.csv.') parser.add_argument('--noreport', action='store_true', dest='noreport', help="Don't create a test results file.") parser.add_argument('tests', metavar='test', nargs='*', help='A test method, test case, module, or directory to run.') return parser
async def unsubscribe(self): try: await self['xep_0060'].unsubscribe(self.pubsub_server, self.node) logging.info('Unsubscribed %s from node %s', self.boundjid.bare, self.node) except XMPPError as error: logging.error('Could not unsubscribe %s from node %s: %s', self.boundjid.bare, self.node, error.format()) if __name__ == '__main__': # Setup the command line arguments. parser = ArgumentParser() parser.version = '%%prog 0.1' parser.usage = "Usage: %%prog [options] <jid> " + \ 'nodes|create|delete|get_configure|purge|subscribe|unsubscribe|publish|retract|get' + \ ' [<node> <data>]' parser.add_argument("-q","--quiet", help="set logging to ERROR", action="store_const", dest="loglevel", const=logging.ERROR, default=logging.INFO) parser.add_argument("-d","--debug", help="set logging to DEBUG", action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.INFO) # JID and password options. parser.add_argument("-j", "--jid", dest="jid",
def createCommandLineParser(prog=None): from argparse import ArgumentParser parser = ArgumentParser(prog=prog) parser.add_argument('paths', nargs='*', default=['.'], help='list of the filename/paths.') parser.add_argument('--version', action='version', version=VERSION) parser.add_argument("-V", "--verbose", help="Output in verbose mode (long function name)", action="store_true", dest="verbose", default=False) parser.add_argument("-C", "--CCN", help = "Threshold for cyclomatic complexity number warning. "+ "The default value is %d. Functions with CCN bigger than this number will generate warning" % DEFAULT_CCN_THRESHOLD, action="store", type=int, dest="CCN", default=DEFAULT_CCN_THRESHOLD) parser.add_argument("-a", "--arguments", help="Limit for number of parameters", action="store", type=int, dest="arguments", default=100) parser.add_argument("-w", "--warnings_only", help="Show warnings only, using clang/gcc's warning format for printing warnings. http://clang.llvm.org/docs/UsersManual.html#cmdoption-fdiagnostics-format", action="store_true", dest="warnings_only", default=False) parser.add_argument("-i", "--ignore_warnings", help="If the number of warnings is equal or less than the number, the tool will exit normally, otherwize it will generate error. Useful in makefile when improving legacy code.", action="store", type=int, dest="number", default=0) parser.add_argument("-x", "--exclude", help="Exclude files that match this pattern. * matches everything, ? matches any single characoter, \"./folder/*\" exclude everything in the folder, recursively. Multiple patterns can be specified. Don't forget to add \"\" around the pattern.", action="append", dest="exclude", default=[]) parser.add_argument("-X", "--xml", help="Generate XML in cppncss style instead of the normal tabular output. Useful to generate report in Jenkins server", action="store_true", dest="xml", default=None) parser.add_argument("-P", "--no_preprocessor_count", help="By default, a #if will also increase the complexity. Adding this option to ignore them", action="store_true", dest="no_preprocessor_count", default=False) parser.add_argument("-t", "--working_threads", help="number of working threads. The default value is 1.", action="store", type=int, dest="working_threads", default=1) parser.add_argument("-d", "--find_duplicates", help="find and skip analysis for identical files. Will be made default in the next release", action="store_true", dest="duplicates", default=False) parser.add_argument("-e", "--display_fn_end_line", help="display function end line number in addition to start line number. Will be made default in the next release", action="store_true", dest="display_fn_end_line", default=False) parser.add_argument("-m", "--modified", help="Calculate modified cyclomatic complexity number", action="store_true", dest="switchCasesAsOneCondition", default=False) parser.add_argument("-E", "--extension", help="under construction...", #"Use extension. Can be WordCount.", action="append", dest="extensions", default=[]) parser.add_argument("-s", "--sort", help="Sort the warning with field. The field can be nloc, cyclomatic_complexity, token_count, parameter_count, etc. Or an customized file.", action="append", dest="sorting", default=[]) parser.usage = "lizard [options] [PATH or FILE] [PATH] ... " parser.description = __doc__ return parser
def config_kraken_socket_parser(subparser: argparse.ArgumentParser): subparser.allow_abbrev = False subparser.set_defaults(func=handle_kraken_websocket) subparser.usage = 'pyton %(prog)s kraken' subparser.description = 'Subscribe to kraken websocket and launches the alert system'
def create_argument_parser(): """Create the argument parser.""" parser = ArgumentParser(add_help=False) parser.usage = "dcovr [--since COMMIT_1] [--until COMMIT_2] [options]" parser.description = \ "A utility to run dcov and summarize the coverage in simple reports." parser.epilog = "See <http://gcovr.com/> for the full manual." # Style guide for option help messages: # - Prefer complete sentences. # - Phrase first sentence as a command: # “Print report”, not “Prints report”. # - Must be readable on the command line, # AND parse as reStructured Text. options = parser.add_argument_group('Options') options.add_argument( "-h", "--help", help="Show this help message, then exit.", action="help" ) options.add_argument( "--version", help="Print the version number, then exit.", action="store_true", dest="version", default=False ) options.add_argument( "-v", "--verbose", help="Print progress messages. " "Please include this output in bug reports.", action="store_true", dest="verbose", default=False ) options.add_argument( "-r", "--report-dir", help="The root directory of your gcovr report files. " "Defaults to '%(default)s', the current directory. " "File names are reported relative to this root. " "The --root is the default --filter.", action="store", dest="source_report_dir", default='.' ) options.add_argument( "--since", help="The start commit in git repo", action="store", dest="since", default=None ) options.add_argument( "--until", help="The end commit in git repo", action="store", dest="until", default=None ) options.add_argument( "--prefix", help="The prefix of the gcovr file", action="store", dest="prefix", default=None ) options.add_argument( "--missing_prefix", help="The missing prefix", action="store", dest="missing_prefix_dir", default="src/" ) output_options = parser.add_argument_group( "Output Options", description="Dcovr prints a html report by default, " ) output_options.add_argument( "-o", "--output", help="Print output to this filename. Defaults to stdout. ", action="store", dest="output", default=None ) output_options.add_argument( "--html-absolute-paths", help="Use absolute paths to link the --html-details reports. " "Defaults to relative links.", action="store_false", dest="relative_anchors", default=True ) output_options.add_argument( "-s", "--print-summary", help="Print a small report to stdout " "with line & branch percentage coverage. " "This is in addition to other reports. " "Default: %(default)s.", action="store_true", dest="print_summary", default=False ) return parser
def get_parser(self): p = ArgumentParser(self.description) p.usage = "create-image [-h] [-f FILE] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument('-f', '--file', help='Image file to upload') return p
async def unsubscribe(self): try: await self['xep_0060'].unsubscribe(self.pubsub_server, self.node) logging.info('Unsubscribed %s from node %s', self.boundjid.bare, self.node) except XMPPError as error: logging.error('Could not unsubscribe %s from node %s: %s', self.boundjid.bare, self.node, error.format()) if __name__ == '__main__': # Setup the command line arguments. parser = ArgumentParser() parser.version = '%%prog 0.1' parser.usage = "Usage: %%prog [options] <jid> " + \ 'nodes|create|delete|get_configure|purge|subscribe|unsubscribe|publish|retract|get' + \ ' [<node> <data>]' parser.add_argument("-q", "--quiet", help="set logging to ERROR", action="store_const", dest="loglevel", const=logging.ERROR, default=logging.INFO) parser.add_argument("-d", "--debug", help="set logging to DEBUG", action="store_const", dest="loglevel", const=logging.DEBUG,
hashvalue = m.hexdigest() print('>>> Extracted Hash =', hashvalue) print('>>> Recorded Hash =', fi.md5()) if hashvalue == fi.md5(): print('>>> MATCH') elif hashvalue != fi.md5(): print('\n *** WARNING ***\nFILE HASH MISMATCH\n') input('Press enter to continue...') ###################################################################### if(__name__=="__main__"): from argparse import ArgumentParser parser = ArgumentParser() parser.usage =\ """ dfxml_xtract.py [args] dfxml imagefile Using the metadata from DFXML file, extract each file object from a target image file. """ parser.add_argument("dfxml",help="Specify the target DFXML file") parser.add_argument("image",help="Specify the target image file") args = parser.parse_args() # Set up output directory for extracted files dfxml_path = os.path.abspath(args.dfxml) image_path = os.path.abspath(args.image) dir_name = os.getcwd() + "/output" if os.path.isdir(dir_name): os.chdir(dir_name)
def update_libpath(options=None): """Find all of the shared libraries in the current virtual environment and modify the activate script to put their directories in LD_LIBRARY_PATH (or its equivalent) """ ldict = {"linux2": "LD_LIBRARY_PATH", "linux": "LD_LIBRARY_PATH", "darwin": "DYLD_LIBRARY_PATH"} libpathvname = ldict[sys.platform] if options is None: parser = ArgumentParser( description="adds any shared library paths found in the current python environment to %s" % libpathvname ) parser.usage = "update_libpath [options]" options = parser.parse_args() if libpathvname: topdir = os.path.dirname(os.path.dirname(sys.executable)) bindir = os.path.join(topdir, "bin") pkgdir = os.path.join(topdir, "lib", "python%s.%s" % sys.version_info[:2], "site-packages") sofiles = [os.path.abspath(x) for x in find_files(pkgdir, "*.so")] final = set() for f in sofiles: pyf = os.path.splitext(f)[0] + ".py" if not os.path.exists(pyf): final.add(os.path.dirname(f)) subdict = {"libpath": libpathvname, "add_on": os.pathsep.join(final)} if len(final) > 0: activate_lines = [ "# BEGIN MODIFICATION\n", 'if [ -z "$%(libpath)s" ] ; then\n', ' %(libpath)s=""\n', "fi\n", "\n", "%(libpath)s=$%(libpath)s:%(add_on)s\n", "export %(libpath)s\n", "# END MODIFICATION\n", "\n", ] absbin = os.path.abspath(bindir) activate_fname = os.path.join(absbin, "activate") with open(activate_fname, "r") as f: lines = f.readlines() try: idx = lines.index(activate_lines[0]) del lines[idx : idx + len(activate_lines)] except ValueError: pass idx = lines.index("export PATH\n") lines[idx + 2 : idx + 2] = activate_lines content = "".join(lines) with open(activate_fname, "w") as f: f.write(content % subdict) print "\nThe 'activate' file has been updated with new values added to %s" % libpathvname print "You must deactivate and reactivate your virtual environment for the" print "changes to take effect\n"
from stack.decorators import as_command @as_command def do(args): ''' sth @argument --sth, help=dowhat, metavar=something ''' print('do %s' % args.sth) The `stack-cli` will parse the `__doc__` of function to the arguments and passes to the `argparse` moudle """ from functools import partial from .decorators import as_command_wrapper, as_wsh_command_wrapper from argparse import ArgumentParser __all__ = ['__version__', 'parser', 'as_command', 'pattern'] __version__ = '0.2.15.5' pattern = {} wsh_pattern = {} parser = ArgumentParser(description='Stack-cli - The Python Tool Stack-cli %s' % __version__) parser.usage = 'stack [-h]' subparsers = parser.add_subparsers(title='Available options:', help='Run `stack COMMAND -h` to get help') as_command = partial(as_command_wrapper, parser=subparsers, mdict=pattern) wsh_command = partial(as_wsh_command_wrapper, mdict=wsh_pattern)
return output.strip() + "\n" if __name__ == "__main__": if sys.version_info[0] == 2 and sys.version_info[1] < 7: sys.stderr.write("Python versions below 2.7 are not supported.\n") sys.stderr.write("Your Python version:\n") sys.stderr.write(".".join([str(v) for v in sys.version_info[:3]]) + "\n") sys.exit(0) from argparse import ArgumentParser, RawDescriptionHelpFormatter parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter) parser.prog = "Coptic NLP Pipeline" parser.usage = "python coptic_nlp.py [OPTIONS] files" parser.epilog = """Example usage: -------------- Add norm, lemma, parse, tag, unary tags, find multiword expressions and do language recognition: > python coptic_nlp.py -penmult infile.txt Just tokenize a file using pipes and dashes: > python coptic_nlp.py -o pipes infile.txt Tokenize with pipes and mark up line breaks, conservatively detokenize bound groups, assume seg boundary at merge site: > python coptic_nlp.py -b -d 1 --segment_merged -o pipes infile.txt Normalize, tag, lemmatize, find multiword expressions and parse, splitting sentences by <verse> tags: > python coptic_nlp.py -pnltm -s verse infile.txt Add full analyses to a whole directory of *.xml files, output to a specified directory:
def config_buda_exchange_parser(subparser: argparse.ArgumentParser): subparser.allow_abbrev = False subparser.set_defaults(func=handle_buda) subparser.usage = 'python %(prog)s buda {btc, eth, ltc, eth}' subparser.description = 'Recover data from Buda.com, transforms it into ohlc and stores it in a csv file' subparser.add_argument('market', choices=['btc', 'eth', 'ltc', 'bch'])
def unsubscribe(self): try: self["xep_0060"].unsubscribe(self.pubsub_server, self.node) print("Unsubscribed %s from node %s" % (self.boundjid.bare, self.node)) except: logging.error("Could not unsubscribe %s from node %s" % (self.boundjid.bare, self.node)) if __name__ == "__main__": # Setup the command line arguments. parser = ArgumentParser() parser.version = "%%prog 0.1" parser.usage = ( "Usage: %%prog [options] <jid> " + "nodes|create|delete|purge|subscribe|unsubscribe|publish|retract|get" + " [<node> <data>]" ) parser.add_argument( "-q", "--quiet", help="set logging to ERROR", action="store_const", dest="loglevel", const=logging.ERROR, default=logging.ERROR, ) parser.add_argument( "-d", "--debug",
def config_create_tables_parser(subparser: argparse.ArgumentParser): subparser.allow_abbrev = False subparser.set_defaults(func=handle_create_tables) subparser.usage = 'pyton %(prog)s create-table' subparser.description = 'Create the database tables based on the vendor provider configured in config.py'
def get_parser(self): p = ArgumentParser(self.description) p.usage = "create-group [-h] [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" return p
if __name__ == "__main__": if sys.version_info[0] == 2 and sys.version_info[1] < 7: sys.stderr.write("Python versions below 2.7 are not supported.\n") sys.stderr.write("Your Python version:\n") sys.stderr.write(".".join([str(v) for v in sys.version_info[:3]]) + "\n") sys.exit(0) from argparse import ArgumentParser, RawDescriptionHelpFormatter parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter) parser.prog = "Coptic NLP Pipeline" parser.usage = "python coptic_nlp.py [OPTIONS] files" parser.epilog = """Example usage: -------------- Add norm, lemma, parse, tag, unary tags, find multiword expressions and do language recognition: > python coptic_nlp.py -penmult infile.txt Just tokenize a file using pipes and dashes: > python coptic_nlp.py -o pipes infile.txt Tokenize with pipes and mark up line breaks, conservatively detokenize bound groups, assume seg boundary at merge site: > python coptic_nlp.py -b -d 1 --segment_merged -o pipes infile.txt Normalize, tag, lemmatize, find multiword expressions and parse, splitting sentences by <verse> tags: > python coptic_nlp.py -pnltm -s verse infile.txt Add full analyses to a whole directory of *.xml files, output to a specified directory:
def main(): parser = ArgumentParser(description='Convert kaldi data directory to uem dat files', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--verbose', type=int, \ dest='verbose', default=0, \ help='Give higher verbose for more logging') parser.add_argument('--get-text', action='store_true', \ help='Get text in dat file') parser.add_argument('--prefix', type=str, \ help='Add db file name as db-<prefix>-{utt/spk}.dat') parser.add_argument('kaldi_dir', \ help='Kaldi data directory') parser.add_argument('output_dir', \ help='Directory to store uem dat files') parser.usage=':'.join(parser.format_usage().split(':')[1:]) \ + 'e.g. : %(prog)s --prefix 203-lao-v0 data/dev10h.seg CMU_db' options = parser.parse_args() if options.get_text: try: text_file = open(options.kaldi_dir+'/text', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/text')) sys.exit(1) try: segments_file = open(options.kaldi_dir+'/segments', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/segments')) sys.exit(1) try: scp_file = open(options.kaldi_dir+'/wav.scp', 'r') except IOError as e: repr(e) sys.stderr.write("%s: No such file %s\n" % (sys.argv[0], options.kaldi_dir+'/wav.scp')) sys.exit(1) reco2file_map = {} for line in scp_file.readlines(): splits = line.strip().split() m = re.search(r".*/(?P<file_name>[0-9A-Za-z_]*\.(sph|wav)).*", line) if not m: sys.stderr.write("%s does not contain a valid speech file (.wav or .sph)\n" % line.strip()) sys.exit(1) reco2file_map[splits[0]] = m.group('file_name') # End for spk2utt_map = {} if options.prefix == None: prefix = options.kaldi_dir.split('/')[-1].split('.')[0] else: prefix = options.prefix try: utt_dat = open(options.output_dir+'/db-'+prefix+'-utt.dat', 'w') spk_dat = open(options.output_dir+'/db-'+prefix+'-spk.dat', 'w') except IOError as e: repr(e) sys.stderr.write("%s: Could not write dat files in %s\n" % (sys.argv[0], options.output_dir)) sys.exit(1) for line in segments_file.readlines(): utt_id, file_id, start, end = line.strip().split() if (options.get_text): splits = text_file.readline().split() while splits[0] < utt_id: splits = text_file.readline().split() text = ' '.join(splits[1:]) else: text = "" utt_dat.write("{UTTID %s} {UTT %s} {SPK %s} {FROM %s} {TO %s} {TEXT %s}\n" % (utt_id, utt_id, file_id, start, end, text)) spk2utt_map.setdefault(file_id, []) spk2utt_map[file_id].append(utt_id) for spk, utts in spk2utt_map.items(): try: spk_dat.write("{SEGS %s} {ADC %s} {CONV %s.wav} {CHANNEL 1} {DUR }\n" % (' '.join(utts), reco2file_map[spk], spk)) except KeyError as e: repr(e) sys.stderr.write("%s: Error in getting file for %s\n" % (sys.argv[0], spk)) sys.exit(1) # End for segments_file.close() utt_dat.close() spk_dat.close()
def arg_parser(prog=None): from argparse import ArgumentParser, Action, ArgumentError class DictAction(Action): # pylint: disable=R0903 def __init__(self, option_strings, dest, nargs=None, **kwargs): super(DictAction, self).__init__(option_strings, dest, **kwargs) def __call__(self, parser, namespace, value, option_string=None): if not re.match(r"\s*\w+\s*=\s*\d+", value): raise ArgumentError(self, "should be like nloc=20") k, val = value.split("=", 2) getattr(namespace, self.dest)[k.strip()] = int(val.strip()) parser = ArgumentParser(prog=prog) parser.add_argument('paths', nargs='*', default=['.'], help='list of the filename/paths.') parser.add_argument('--version', action='version', version=VERSION) parser.add_argument("-l", "--languages", help='''List the programming languages you want to analyze. if left empty, it'll search for all languages it knows. `lizard -l cpp -l java`searches for C++ and Java code. The available languages are: ''' + ', '.join(x.language_names[0] for x in languages()), action="append", dest="languages", default=[]) parser.add_argument("-V", "--verbose", help="Output in verbose mode (long function name)", action="store_true", dest="verbose", default=False) parser.add_argument("-C", "--CCN", help='''Threshold for cyclomatic complexity number warning. The default value is %d. Functions with CCN bigger than it will generate warning ''' % DEFAULT_CCN_THRESHOLD, type=int, dest="CCN", default=DEFAULT_CCN_THRESHOLD) parser.add_argument("-L", "--length", help='''Threshold for maximum function length warning. The default value is %d. Functions length bigger than it will generate warning ''' % DEFAULT_MAX_FUNC_LENGTH, type=int, dest="length", default=DEFAULT_MAX_FUNC_LENGTH) parser.add_argument("-a", "--arguments", help="Limit for number of parameters", type=int, dest="arguments", default=100) parser.add_argument("-w", "--warnings_only", help='''Show warnings only, using clang/gcc's warning format for printing warnings. http://clang.llvm.org/docs/UsersManual.html#cmdoption-fdiagnostics-format ''', action="store_const", const=print_clang_style_warning, dest="printer") parser.add_argument("-i", "--ignore_warnings", help='''If the number of warnings is equal or less than the number, the tool will exit normally, otherwise it will generate error. Useful in makefile for legacy code.''', type=int, dest="number", default=0) parser.add_argument("-x", "--exclude", help='''Exclude files that match this pattern. * matches everything, ? matches any single character, "./folder/*" exclude everything in the folder recursively. Multiple patterns can be specified. Don't forget to add "" around the pattern.''', action="append", dest="exclude", default=[]) parser.add_argument("-t", "--working_threads", help='''number of working threads. The default value is 1. Using a bigger number can fully utilize the CPU and often faster.''', type=int, dest="working_threads", default=1) parser.add_argument("-X", "--xml", help='''Generate XML in cppncss style instead of the tabular output. Useful to generate report in Jenkins server''', action="store_const", const=print_xml, dest="printer") parser.add_argument("-H", "--html", help='''Output HTML report''', action="store_const", const=html_output, dest="printer") parser.add_argument("-m", "--modified", help="Calculate modified cyclomatic complexity number", action="append_const", const="modified", dest="extensions", default=[]) _extension_arg(parser) parser.add_argument("-s", "--sort", help='''Sort the warning with field. The field can be nloc, cyclomatic_complexity, token_count, p#arameter_count, etc. Or an customized field.''', action="append", dest="sorting", default=[]) parser.add_argument("-T", "--Threshold", help='''Set the limit for a field. The field can be nloc, cyclomatic_complexity, token_count, parameter_count, etc. Or an customized file. Lizard will report warning if a function exceed the limit''', action=DictAction, dest="thresholds", default={}) parser.add_argument("-W", "--whitelist", help='''The path and file name to the whitelist file. It's './whitelizard.txt' by default. Find more information in README.''', type=str, dest="whitelist", default=DEFAULT_WHITELIST) parser.usage = '''lizard [options] [PATH or FILE] [PATH] ...''' parser.description = __doc__ return parser
def main(): """Main entry point of generator""" apt_pkg.init() parser = ArgumentParser(description="Generate DEP-11 metadata from Debian packages.") parser.add_argument('subcommand', help="The command that should be executed.") parser.add_argument('parameters', nargs='*', help="Parameters for the subcommand.") parser.usage = "\n" parser.usage += " process [CONFDIR] [SUITE] - Process packages and extract metadata.\n" parser.usage += " cleanup [CONFDIR] - Remove unused data from the cache and expire media.\n" parser.usage += " update-html [CONFDIR] - Re-generate the metadata and issue HTML pages.\n" parser.usage += " removed-processed [CONFDIR] [SUITE] - Remove information about processed or failed components.\n" args = parser.parse_args() command = args.subcommand params = args.parameters # configure logging log_level = log.INFO if os.environ.get("DEBUG"): log_level = log.DEBUG log.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=log_level) if command == "process": if len(params) != 2: print("Invalid number of arguments: You need to specify a DEP-11 data dir and suite.") sys.exit(1) gen = DEP11Generator() ret = gen.initialize(params[0]) if not ret: print("Initialization failed, can not continue.") sys.exit(2) gen.process_suite(params[1]) elif command == "cleanup": if len(params) != 1: print("Invalid number of arguments: You need to specify a DEP-11 data dir.") sys.exit(1) gen = DEP11Generator() ret = gen.initialize(params[0]) if not ret: print("Initialization failed, can not continue.") sys.exit(2) gen.expire_cache() elif command == "update-html": if len(params) != 1: print("Invalid number of arguments: You need to specify a DEP-11 data dir.") sys.exit(1) hgen = HTMLGenerator() ret = hgen.initialize(params[0]) if not ret: print("Initialization failed, can not continue.") sys.exit(2) hgen.update_html() elif command == "remove-processed": if len(params) != 2: print("Invalid number of arguments: You need to specify a DEP-11 data dir and suite.") sys.exit(1) gen = DEP11Generator() ret = gen.initialize(params[0]) if not ret: print("Initialization failed, can not continue.") sys.exit(2) gen.remove_processed(params[1]) else: print("Run with --help for a list of available command-line options!")
def parse_arguments(args): """ Create and parse arguments. """ parser = ArgumentParser(add_help=False) parser.usage = "gcovr [options] [search_paths...]" parser.description = \ "A utility to run gcov and summarize the coverage in simple reports." parser.epilog = "See <http://gcovr.com/> for the full manual." # Style guide for option help messages: # - Prefer complete sentences. # - Phrase first sentence as a command: # “Print report”, not “Prints report”. options = parser.add_argument_group('Options') options.add_argument("-h", "--help", help="Show this help message, then exit.", action="help") options.add_argument("--version", help="Print the version number, then exit.", action="store_true", dest="version", default=False) options.add_argument("-v", "--verbose", help="Print progress messages. " "Please include this output in bug reports.", action="store_true", dest="verbose", default=False) options.add_argument("-r", "--root", help="The root directory of your source files. " "Defaults to '%(default)s', the current directory. " "File names are reported relative to this root. " "The --root is the default --filter.", action="store", dest="root", default='.') options.add_argument( 'search_paths', help="Search these directories for coverage files. " "Defaults to --root and --object-directory.", nargs='*', ) options.add_argument( "--fail-under-line", type=check_percentage, metavar="MIN", help="Exit with a status of 2 " "if the total line coverage is less than MIN. " "Can be ORed with exit status of '--fail-under-branch' option.", action="store", dest="fail_under_line", default=0.0) options.add_argument( "--fail-under-branch", type=check_percentage, metavar="MIN", help="Exit with a status of 4 " "if the total branch coverage is less than MIN. " "Can be ORed with exit status of '--fail-under-line' option.", action="store", dest="fail_under_branch", default=0.0) output_options = parser.add_argument_group( "Output Options", description="Gcovr prints a text report by default, " "but can switch to XML or HTML.") output_options.add_argument( "-o", "--output", help="Print output to this filename. Defaults to stdout. " "Required for --html-details.", action="store", dest="output", default=None) output_options.add_argument( "-b", "--branches", help="Report the branch coverage instead of the line coverage. " "For text report only.", action="store_true", dest="show_branch", default=None) output_options.add_argument( "-u", "--sort-uncovered", help="Sort entries by increasing number of uncovered lines. " "For text and HTML report.", action="store_true", dest="sort_uncovered", default=None) output_options.add_argument( "-p", "--sort-percentage", help="Sort entries by increasing percentage of uncovered lines. " "For text and HTML report.", action="store_true", dest="sort_percent", default=None) output_options.add_argument("-x", "--xml", help="Generate a Cobertura XML report.", action="store_true", dest="xml", default=False) output_options.add_argument( "--xml-pretty", help= "Pretty-print the XML report. Implies --xml. Default: %(default)s.", action="store_true", dest="prettyxml", default=False) output_options.add_argument("--html", help="Generate a HTML report.", action="store_true", dest="html", default=False) output_options.add_argument( "--html-details", help="Add annotated source code reports to the HTML report. " "Requires --output as a basename for the reports. " "Implies --html.", action="store_true", dest="html_details", default=False) output_options.add_argument( "--html-absolute-paths", help="Use absolute paths to link the --html-details reports. " "Defaults to relative links.", action="store_false", dest="relative_anchors", default=True) output_options.add_argument( '--html-encoding', help="Override the declared HTML report encoding. " "Defaults to %(default)s. " "May be necessary for unusual source file encodings. " "Encoding support is likely to change in the future.", action='store', dest='html_encoding', default='UTF-8') output_options.add_argument("-s", "--print-summary", help="Print a small report to stdout " "with line & branch percentage coverage. " "This is in addition to other reports. " "Default: %(default)s.", action="store_true", dest="print_summary", default=False) filter_options = parser.add_argument_group( "Filter Options", description="Filters decide which files are included in the report. " "Any filter must match, and no exclude filter must match. " "A filter is a regular expression that matches a path. " "On Windows, the filter must match a relative path.") filter_options.add_argument( "-f", "--filter", help="Keep only source files that match this filter. " "Can be specified multiple times. " "If no filters are provided, defaults to --root.", action="append", dest="filter", default=[]) filter_options.add_argument( "-e", "--exclude", help="Exclude source files that match this filter. " "Can be specified multiple times.", action="append", dest="exclude", default=[]) filter_options.add_argument( "--gcov-filter", help="Keep only gcov data files that match this filter. " "Can be specified multiple times.", action="append", dest="gcov_filter", default=[]) filter_options.add_argument( "--gcov-exclude", help="Exclude gcov data files that match this filter. " "Can be specified multiple times.", action="append", dest="gcov_exclude", default=[]) filter_options.add_argument( "--exclude-directories", help="Exclude directories that match this regex " "while searching raw coverage files. " "Can be specified multiple times.", action="append", dest="exclude_dirs", default=[]) gcov_options = parser.add_argument_group( "GCOV Options", "The 'gcov' tool turns raw coverage files (*.gcda and *.gcno) " "into *.gcov files that are then processed by gcovr. " "The gcno files are generated by the compiler. " "The gcda files are generated when the instrumented program is executed." ) gcov_options.add_argument("--gcov-executable", help="Use a particular gcov executable. " "Must match the compiler you are using, " "e.g. 'llvm-cov gcov' for Clang. " "Can include additional arguments. " "Defaults to the GCOV environment variable, " "or 'gcov': '%(default)s'.", action="store", dest="gcov_cmd", default=os.environ.get('GCOV', 'gcov')) gcov_options.add_argument( "--exclude-unreachable-branches", help="Exclude branch coverage with LCOV/GCOV exclude markers. " "Additionally, exclude branch coverage from lines " "without useful source code " "(often, compiler-generated \"dead\" code). " "Default: %(default)s.", action="store_true", dest="exclude_unreachable_branches", default=False) gcov_options.add_argument( "-g", "--use-gcov-files", help="Use existing gcov files for analysis. Default: %(default)s.", action="store_true", dest="gcov_files", default=False) gcov_options.add_argument( '--gcov-ignore-parse-errors', help="Skip lines with parse errors in GCOV files " "instead of exiting with an error. " "A report will be shown on stderr. " "Default: %(default)s.", action="store_true", dest="gcov_ignore_parse_errors", default=False) gcov_options.add_argument( '--object-directory', help="Override normal working directory detection. " "Gcovr needs to identify the path between gcda files " "and the directory where the compiler was originally run. " "Normally, gcovr can guess correctly. " "This option specifies either " "the path from gcc to the gcda file (i.e. gcc's '-o' option), " "or the path from the gcda file to gcc's working directory.", action="store", dest="objdir", default=None) gcov_options.add_argument( "-k", "--keep", help="Keep gcov files after processing. " "This applies both to files that were generated by gcovr, " "or were supplied via the --use-gcov-files option. " "Default: %(default)s.", action="store_true", dest="keep", default=False) gcov_options.add_argument( "-d", "--delete", help="Delete gcda files after processing. Default: %(default)s.", action="store_true", dest="delete", default=False) return parser.parse_args(args=args)
def update_libpath(options=None): """Find all of the shared libraries in the current virtual environment and modify the activate script to put their directories in LD_LIBRARY_PATH (or its equivalent) """ ldict = { 'linux2': 'LD_LIBRARY_PATH', 'linux': 'LD_LIBRARY_PATH', 'darwin': 'DYLD_LIBRARY_PATH', } libpathvname = ldict[sys.platform] if options is None: parser = ArgumentParser(description="adds any shared library paths" " found in the current python environment to" " %s" % libpathvname) parser.usage = "update_libpath [options]" options = parser.parse_args() if libpathvname: topdir = os.path.dirname(os.path.dirname(sys.executable)) bindir = os.path.join(topdir, 'bin') pkgdir = os.path.join(topdir, 'lib', 'python%s.%s' % sys.version_info[:2], 'site-packages') sofiles = [os.path.abspath(x) for x in find_files(pkgdir, '*.so')] final = set() for fname in sofiles: pyf = os.path.splitext(fname)[0]+'.py' if not os.path.exists(pyf): final.add(os.path.dirname(fname)) subdict = { 'libpath': libpathvname, 'add_on': os.pathsep.join(final) } if len(final) > 0: activate_lines = [ '# BEGIN MODIFICATION\n', 'if [ -z "$%(libpath)s" ] ; then\n', ' %(libpath)s=""\n', 'fi\n', '\n', '%(libpath)s=$%(libpath)s:%(add_on)s\n', 'export %(libpath)s\n', '# END MODIFICATION\n', '\n', ] absbin = os.path.abspath(bindir) activate_fname = os.path.join(absbin, 'activate') with open(activate_fname, 'r') as inp: lines = inp.readlines() try: idx = lines.index(activate_lines[0]) del lines[idx:idx+len(activate_lines)] except ValueError: pass idx = lines.index('export PATH\n') lines[idx+2:idx+2] = activate_lines content = ''.join(lines) with open(activate_fname, 'w') as out: out.write(content % subdict) print "\nThe 'activate' file has been updated with new values" \ " added to %s" % libpathvname print "You must deactivate and reactivate your virtual environment" print "for thechanges to take effect\n"
def get_parser(self): p = ArgumentParser(self.description) p.usage = "modify-image [-h] image [--metadata value [--metadata value ...]]" p.epilog = "See documentation for a list of required and optional metadata" p.add_argument('image', help='The existing image you want to modify') return p
@as_command def do(args): ''' sth @argument --sth, help=dowhat, metavar=something ''' print('do %s' % args.sth) The `stack-cli` will parse the `__doc__` of function to the arguments and passes to the `argparse` moudle """ from functools import partial from .decorators import as_command_wrapper, as_wsh_command_wrapper from argparse import ArgumentParser __all__ = ['__version__', 'parser', 'as_command', 'pattern'] __version__ = '0.2.15.5' pattern = {} wsh_pattern = {} parser = ArgumentParser( description='Stack-cli - The Python Tool Stack-cli %s' % __version__) parser.usage = 'stack [-h]' subparsers = parser.add_subparsers(title='Available options:', help='Run `stack COMMAND -h` to get help') as_command = partial(as_command_wrapper, parser=subparsers, mdict=pattern) wsh_command = partial(as_wsh_command_wrapper, mdict=wsh_pattern)
def create_command_line_parser(prog=None): from argparse import ArgumentParser parser = ArgumentParser(prog=prog) parser.add_argument('paths', nargs='*', default=['.'], help='list of the filename/paths.') parser.add_argument('--version', action='version', version=VERSION) parser.add_argument("-V", "--verbose", help="Output in verbose mode (long function name)", action="store_true", dest="verbose", default=False) parser.add_argument("-C", "--CCN", help='''Threshold for cyclomatic complexity number warning. The default value is %d. Functions with CCN bigger than it will generate warning ''' % DEFAULT_CCN_THRESHOLD, type=int, dest="CCN", default=DEFAULT_CCN_THRESHOLD) parser.add_argument("-L", "--length", help='''Threshold for maximum function length warning. The default value is %d. Functions length bigger than it will generate warning ''' % DEFAULT_MAX_FUNC_LENGTH, type=int, dest="length", default=DEFAULT_MAX_FUNC_LENGTH) parser.add_argument("-a", "--arguments", help="Limit for number of parameters", type=int, dest="arguments", default=100) parser.add_argument("-w", "--warnings_only", help='''Show warnings only, using clang/gcc's warning format for printing warnings. http://clang.llvm.org/docs/UsersManual.html#cmdoption-fdiagnostics-format ''', action="store_true", dest="warnings_only", default=False) parser.add_argument("-i", "--ignore_warnings", help='''If the number of warnings is equal or less than the number, the tool will exit normally, otherwise it will generate error. Useful in makefile for legacy code.''', type=int, dest="number", default=0) parser.add_argument("-x", "--exclude", help='''Exclude files that match this pattern. * matches everything, ? matches any single character, "./folder/*" exclude everything in the folder recursively. Multiple patterns can be specified. Don't forget to add "" around the pattern.''', action="append", dest="exclude", default=[]) parser.add_argument("-X", "--xml", help='''Generate XML in cppncss style instead of the tabular output. Useful to generate report in Jenkins server''', action="store_true", dest="xml", default=None) parser.add_argument("-t", "--working_threads", help='''number of working threads. The default value is 1. Using a bigger number can fully utilize the CPU and often faster.''', type=int, dest="working_threads", default=1) parser.add_argument("-m", "--modified", help="Calculate modified cyclomatic complexity number", action="store_true", dest="switchCasesAsOneCondition", default=False) parser.add_argument("-E", "--extension", help='''User the extensions. The available extensions are: -Ecpre: it will ignore code in the #else branch. -Ewordcount: count word frequencies and generate tag cloud. -Eoutside: include the global code as one function. ''', action="append", dest="extensions", default=[]) parser.add_argument("-s", "--sort", help='''Sort the warning with field. The field can be nloc, cyclomatic_complexity, token_count, parameter_count, etc. Or an customized file.''', action="append", dest="sorting", default=[]) parser.add_argument("-W", "--whitelist", help='''The path and file name to the whitelist file. It's './whitelizard.txt' by default.''', type=str, dest="whitelist", default=DEFAULT_WHITELIST) parser.usage = '''lizard [options] [PATH or FILE] [PATH] ...''' parser.description = __doc__ return parser
def config_crypto_compare_parser(subparser: argparse.ArgumentParser): subparser.allow_abbrev = False subparser.set_defaults(func=handle_crypto_compare) subparser.usage = 'python %(prog)s cryptoCompare {btc, eth, ltc, eth}' subparser.description = 'Recovers data from cryptocompare.com and stores it in a csv file' subparser.add_argument('market', choices=['btc', 'eth', 'ltc', 'bch'])
def unittest(args): """run the JUnit tests""" junit_arg_actions = [] junit_args = [] class MxJUnitWrapperArg(Action): def __init__(self, **kwargs): kwargs['required'] = False Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) junit_args.append(values) class MxJUnitWrapperBoolArg(Action): def __init__(self, **kwargs): kwargs['required'] = False kwargs['nargs'] = 0 Action.__init__(self, **kwargs) junit_arg_actions.append(self) def __call__(self, parser, namespace, values, option_string=None): junit_args.append('-' + self.dest) parser = ArgumentParser( prog='mx unittest', description='run the JUnit tests', formatter_class=RawDescriptionHelpFormatter, epilog=unittestHelpSuffix, ) parser.add_argument('--blacklist', help='run all testcases not specified in <file>', metavar='<file>') parser.add_argument('--whitelist', help='run testcases specified in <file> only', metavar='<file>') parser.add_argument('--verbose', help='enable verbose JUnit output', dest='JUnitVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument('--very-verbose', help='enable very verbose JUnit output', dest='JUnitVeryVerbose', action=MxJUnitWrapperBoolArg) parser.add_argument( '--max-class-failures', help= 'stop after N test classes that have a failure (default is no limit)', metavar='<N>', dest='JUnitMaxClassFailures', action=MxJUnitWrapperArg) parser.add_argument('--fail-fast', help='alias for --max-class-failures=1', dest='JUnitFailFast', action=MxJUnitWrapperBoolArg) parser.add_argument( '--enable-timing', help='enable JUnit test timing (requires --verbose/--very-verbose)', dest='JUnitEnableTiming', action=MxJUnitWrapperBoolArg) parser.add_argument( '--regex', help='run only testcases matching a regular expression', metavar='<regex>') parser.add_argument('--color', help='enable color output', dest='JUnitColor', action=MxJUnitWrapperBoolArg) parser.add_argument('--gc-after-test', help='force a GC after each test', dest='JUnitGCAfterTest', action=MxJUnitWrapperBoolArg) parser.add_argument( '--record-results', help='record test class results to passed.txt and failed.txt', dest='JUnitRecordResults', action=MxJUnitWrapperBoolArg) parser.add_argument('--suite', help='run only the unit tests in <suite>', metavar='<suite>') parser.add_argument('--repeat', help='run each test <n> times', dest='JUnitRepeat', action=MxJUnitWrapperArg, type=is_strictly_positive, metavar='<n>') parser.add_argument( '--open-packages', dest='JUnitOpenPackages', action=MxJUnitWrapperArg, metavar='<module>/<package>[=<target-module>(,<target-module>)*]', help= "export and open packages regardless of module declarations (see more detail and examples below)" ) eagerStacktrace = parser.add_mutually_exclusive_group() eagerStacktrace.add_argument( '--eager-stacktrace', action='store_const', const=True, dest='eager_stacktrace', help='print test errors as they occur (default)') eagerStacktrace.add_argument( '--no-eager-stacktrace', action='store_const', const=False, dest='eager_stacktrace', help='print test errors after all tests have run') # Augment usage text to mention test filters and options passed to the VM usage = parser.format_usage().strip() if usage.startswith('usage: '): usage = usage[len('usage: '):] parser.usage = usage + ' [test filters...] [VM options...]' ut_args = [] delimiter = False # check for delimiter while len(args) > 0: arg = args.pop(0) if arg == '--': delimiter = True break ut_args.append(arg) if delimiter: # all arguments before '--' must be recognized parsed_args = parser.parse_args(ut_args) else: # parse all known arguments parsed_args, args = parser.parse_known_args(ut_args) # Remove junit_args values from parsed_args for a in junit_arg_actions: parsed_args.__dict__.pop(a.dest) if parsed_args.whitelist: try: with open(parsed_args.whitelist) as fp: parsed_args.whitelist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read whitelist: ' + parsed_args.whitelist) if parsed_args.blacklist: try: with open(parsed_args.blacklist) as fp: parsed_args.blacklist = [ re.compile(fnmatch.translate(l.rstrip())) for l in fp.readlines() if not l.startswith('#') ] except IOError: mx.log('warning: could not read blacklist: ' + parsed_args.blacklist) if parsed_args.eager_stacktrace is None: junit_args.append('-JUnitEagerStackTrace') parsed_args.__dict__.pop('eager_stacktrace') _unittest(args, ['@Test', '@Parameters'], junit_args, **parsed_args.__dict__)
def _get_parser(): """Returns a parser to handle command line args.""" parser = ArgumentParser() parser.usage = "testflo [options]" parser.add_argument('-c', '--config', action='store', dest='cfg', metavar='CONFIG', help='Path of config file where preferences are specified.') parser.add_argument('-t', '--testfile', action='store', dest='testfile', metavar='TESTFILE', help='Path to a file containing one testspec per line.') parser.add_argument('--maxtime', action='store', dest='maxtime', metavar='TIME_LIMIT', default=-1, type=float, help='Specifies a time limit for tests to be saved to ' 'the quicktests.in file.') try: cpus = cpu_count() except: warnings.warn('CPU count could not be determined. Defaulting to 1') cpus = 1 parser.add_argument('-n', '--numprocs', type=int, action='store', dest='num_procs', metavar='NUM_PROCS', default=cpus, help='Number of processes to run. By default, this will ' 'use the number of CPUs available. To force serial' ' execution, specify a value of 1.') parser.add_argument('-o', '--outfile', action='store', dest='outfile', metavar='OUTFILE', default='test_report.out', help='Name of test report file. Default is test_report.out.') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='Include testspec and elapsed time in ' 'screen output.') parser.add_argument('--dryrun', action='store_true', dest='dryrun', help="Don't actually run tests, but print " "which tests would have been run.") parser.add_argument('-i', '--isolated', action='store_true', dest='isolated', help="Run each test in a separate subprocess." " This is required to run MPI tests.") parser.add_argument('-x', '--stop', action='store_true', dest='stop', help="Stop after the first test failure, or as soon as possible" " when running concurrent tests.") parser.add_argument('-s', '--nocapture', action='store_true', dest='nocapture', help="Standard output (stdout) will not be captured and will be" " written to the screen immediately.") parser.add_argument('--coverage', action='store_true', dest='coverage', help="Perform coverage analysis and display results on stdout") parser.add_argument('--coverage-html', action='store_true', dest='coveragehtml', help="Perform coverage analysis and display results in browser") parser.add_argument('--coverpkg', action='append', dest='coverpkgs', metavar='COVERPKG', help="Add the given package to the coverage list. You" " can use this option multiple times to cover" " multiple packages.") parser.add_argument('--profile', action='store_true', dest='profile', help="Perform profiling.") parser.add_argument('--profile_port', action='store', dest='prof_port', default=4242, type=int, help='Port used for profile viewer server.') parser.add_argument('--noreport', action='store_true', dest='noreport', help="Don't create a test results file.") parser.add_argument('tests', metavar='test', nargs='*', help='A test method, test case, module, or directory to run.') return parser
def arg_parser(prog=None): from argparse import ArgumentParser, Action, ArgumentError class DictAction(Action): # pylint: disable=R0903 def __init__(self, option_strings, dest, nargs=None, **kwargs): super(DictAction, self).__init__(option_strings, dest, **kwargs) def __call__(self, parser, namespace, value, option_string=None): if not re.match(r"\s*\w+\s*=\s*\d+", value): raise ArgumentError(self, "should be like nloc=20") k, val = value.split("=", 2) getattr(namespace, self.dest)[k.strip()] = int(val.strip()) parser = ArgumentParser(prog=prog) parser.add_argument('paths', nargs='*', default=['.'], help='list of the filename/paths.') parser.add_argument('--version', action='version', version=version) parser.add_argument("-l", "--languages", help='''List the programming languages you want to analyze. if left empty, it'll search for all languages it knows. `lizard -l cpp -l java`searches for C++ and Java code. The available languages are: ''' + ', '.join(x.language_names[0] for x in languages()), action="append", dest="languages", default=[]) parser.add_argument("-V", "--verbose", help="Output in verbose mode (long function name)", action="store_true", dest="verbose", default=False) parser.add_argument("-C", "--CCN", help='''Threshold for cyclomatic complexity number warning. The default value is %d. Functions with CCN bigger than it will generate warning ''' % DEFAULT_CCN_THRESHOLD, type=int, dest="CCN", default=DEFAULT_CCN_THRESHOLD) parser.add_argument("-f", "--input_file", help='''get a list of filenames from the given file ''', type=str, dest="input_file") parser.add_argument("-L", "--length", help='''Threshold for maximum function length warning. The default value is %d. Functions length bigger than it will generate warning ''' % DEFAULT_MAX_FUNC_LENGTH, type=int, dest="length", default=DEFAULT_MAX_FUNC_LENGTH) parser.add_argument("-a", "--arguments", help="Limit for number of parameters", type=int, dest="arguments", default=100) parser.add_argument("-w", "--warnings_only", help='''Show warnings only, using clang/gcc's warning format for printing warnings. http://clang.llvm.org/docs/UsersManual.html#cmdoption-fdiagnostics-format ''', action="store_const", const=print_clang_style_warning, dest="printer") parser.add_argument("--warning-msvs", help='''Show warnings only, using Visual Studio's warning format for printing warnings. https://msdn.microsoft.com/en-us/library/yxkt8b26.aspx ''', action="store_const", const=print_msvs_style_warning, dest="printer") parser.add_argument("-i", "--ignore_warnings", help='''If the number of warnings is equal or less than the number, the tool will exit normally; otherwise, it will generate error. If the number is negative, the tool exits normally regardless of the number of warnings. Useful in makefile for legacy code.''', type=int, dest="number", default=0) parser.add_argument("-x", "--exclude", help='''Exclude files that match the pattern. * matches everything, ? matches any single character, "./folder/*" exclude everything in the folder recursively. Multiple patterns can be specified. Don't forget to add "" around the pattern.''', action="append", dest="exclude", default=[]) parser.add_argument("-t", "--working_threads", help='''number of working threads. The default value is 1. Using a bigger number can fully utilize the CPU and often faster.''', type=int, dest="working_threads", default=1) parser.add_argument("-X", "--xml", help='''Generate XML in cppncss style instead of the tabular output. Useful to generate report in Jenkins server''', action="store_const", const=print_xml, dest="printer") parser.add_argument("--csv", help='''Generate CSV output as a transform of the default output''', action="store_const", const=print_csv, dest="printer") parser.add_argument("-H", "--html", help='''Output HTML report''', action="store_const", const=html_output, dest="printer") parser.add_argument("-m", "--modified", help='''Calculate modified cyclomatic complexity number , which count a switch/case with multiple cases as one CCN.''', action="append_const", const="modified", dest="extensions", default=[]) _extension_arg(parser) parser.add_argument("-s", "--sort", help='''Sort the warning with field. The field can be nloc, cyclomatic_complexity, token_count, p#arameter_count, etc. Or an customized field.''', action="append", dest="sorting", default=[]) parser.add_argument("-T", "--Threshold", help='''Set the limit for a field. The field can be nloc, cyclomatic_complexity, token_count, parameter_count, etc. Or an customized file. Lizard will report warning if a function exceed the limit''', action=DictAction, dest="thresholds", default={}) parser.add_argument("-W", "--whitelist", help='''The path and file name to the whitelist file. It's './whitelizard.txt' by default. Find more information in README.''', type=str, dest="whitelist", default=DEFAULT_WHITELIST) parser.usage = '''lizard [options] [PATH or FILE] [PATH] ...''' parser.description = __doc__ return parser
cdata = None import xml.parsers.expat p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data p.ParseFile(open(fn)) if (__name__ == '__main__'): from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter global args parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.usage =\ """ prog [args] file1 [file2...] --- hash files and produce DFXML [args] dir1 [dir2...] --- hash dirs and produce DFXML You can also extract a set of hashes to stdout with: [--md5 | --sha1 | --sha256] --extract=filename.xml Note: MD5 output is assumed unless another hash algorithm is specified. """ parser.add_argument('--piecewise', help='Specifies size of piecewise hashes', default=0, type=int) parser.add_argument( '--addfixml', help='Specifies XML to add to each file object (for labeling)')
def update_libpath(options=None): """Find all of the shared libraries in the current virtual environment and modify the activate script to put their directories in LD_LIBRARY_PATH (or its equivalent). """ ldict = { 'linux2': 'LD_LIBRARY_PATH', 'linux': 'LD_LIBRARY_PATH', 'darwin': 'DYLD_LIBRARY_PATH', } libpathvname = ldict[sys.platform] if options is None: parser = ArgumentParser(description="adds any shared library paths" " found in the current python environment to" " %s" % libpathvname) parser.usage = "update_libpath [options]" options = parser.parse_args() if libpathvname: topdir = os.path.dirname(os.path.dirname(sys.executable)) bindir = os.path.join(topdir, 'bin') pkgdir = os.path.join(topdir, 'lib', 'python%s.%s' % sys.version_info[:2], 'site-packages') sofiles = [os.path.abspath(x) for x in find_files(pkgdir, '*.so')] final = set() for fname in sofiles: pyf = os.path.splitext(fname)[0] + '.py' if not os.path.exists(pyf): final.add(os.path.dirname(fname)) subdict = {'libpath': libpathvname, 'add_on': os.pathsep.join(final)} if len(final) > 0: activate_lines = [ '# BEGIN MODIFICATION\n', 'if [ -z "$%(libpath)s" ] ; then\n', ' %(libpath)s=""\n', 'fi\n', '\n', '%(libpath)s=$%(libpath)s:%(add_on)s\n', 'export %(libpath)s\n', '# END MODIFICATION\n', '\n', ] absbin = os.path.abspath(bindir) activate_fname = os.path.join(absbin, 'activate') with open(activate_fname, 'r') as inp: lines = inp.readlines() try: idx = lines.index(activate_lines[0]) del lines[idx:idx + len(activate_lines)] except ValueError: pass idx = lines.index('export PATH\n') lines[idx + 2:idx + 2] = activate_lines content = ''.join(lines) with open(activate_fname, 'w') as out: out.write(content % subdict) print "\nThe 'activate' file has been updated with new values" \ " added to %s" % libpathvname print "You must deactivate and reactivate your virtual environment" print "for the changes to take effect\n"
else: pstr = lambda: promptstr if cmd and port: def prompt(): port.write(cmd) incoming = fmt(port.readline()).strip() return raw_input(incoming + pstr()) else: prompt = lambda: raw_input(pstr()) return prompt ### Setup commandline arguments ### parser = ArgumentParser() parser.usage = "%(prog)s device [command, ...] [options]" parser.description = "A dumb serial terminal" parser.epilog = """This 'terminal' waits for user input, sends it and prints any replies. To fetch possible responses without sending anything just hit return. Use CTRL-D or CTRL-C to quit.""" parser.add_argument("device", help="serial device to open") parser.add_argument("commands", nargs='*', help="send commands and exit after response") parser.add_argument("-v", "--version", action="version", version="%(prog)s "+__version__) parser.add_argument("-q", "--quiet", action="store_true", help="don't print responses to stdout") parser.add_argument("--baudrate", metavar="BAUD", default=115200, type=int, help="set baudrate (115200)") parser.add_argument("--timeout", metavar="SEC", default=0.5, type=float, help="set read timeout (0.5)") parser.add_argument("--logfile", metavar="FILE", type=FileType(mode="w"), help="log everything to FILE") parser.add_argument("--eol", default="lf", choices=["lf", "crlf", "cr", "lfcr", "none"], help="choose end of line characters (lf)")