Python dateutil.parser.parse_args() Examples
The following are 30
code examples of dateutil.parser.parse_args().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
dateutil.parser
, or try the search function
.
Example #1
Source File: dns-domain-expiration-checker.py From dns-domain-expiration-checker with GNU General Public License v2.0 | 6 votes |
def processcli(): """ parses the CLI arguments and returns a domain or a file with a list of domains. """ parser = argparse.ArgumentParser(description='DNS Statistics Processor') parser.add_argument('--domainfile', help="Path to file with list of domains and expiration intervals.") parser.add_argument('--domainname', help="Domain to check expiration on.") parser.add_argument('--email', action="store_true", help="Enable debugging output.") parser.add_argument('--interactive',action="store_true", help="Enable debugging output.") parser.add_argument('--expiredays', default=10000, type=int, help="Expiration threshold to check against.") parser.add_argument('--sleeptime', default=60, type=int, help="Time to sleep between whois queries.") parser.add_argument('--smtpserver', default="localhost", help="SMTP server to use.") parser.add_argument('--smtpport', default=25, help="SMTP port to connect to.") parser.add_argument('--smtpto', default="root", help="SMTP To: address.") parser.add_argument('--smtpfrom', default="root", help="SMTP From: address.") # Return a dict() with all of the arguments passed in return(vars(parser.parse_args()))
Example #2
Source File: delete_old_marathon_deployments.py From paasta with Apache License 2.0 | 6 votes |
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "-a", "--age", dest="age", type=timedelta_type, default="1h", help="Max age of a Marathon deployment before it is stopped." "Any pytimeparse unit is supported", ) parser.add_argument( "-n", "--dry-run", action="store_true", help="Don't actually stop any Marathon deployments", ) parser.add_argument("-v", "--verbose", action="store_true") options = parser.parse_args() return options
Example #3
Source File: delete_old_marathon_deployments.py From paasta with Apache License 2.0 | 6 votes |
def main(): args = parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) clients = marathon_tools.get_list_of_marathon_clients() for client in clients: for deployment in client.list_deployments(): delete_deployment_if_too_old( client=client, deployment=deployment, max_date=args.age, dry_run=args.dry_run, )
Example #4
Source File: gh2arthur.py From grimoirelab-elk with GNU General Public License v3.0 | 5 votes |
def get_params(): parser = get_params_parser() args = parser.parse_args() if not args.org or not args.token: parser.error("token and org params must be provided.") sys.exit(1) return args
Example #5
Source File: test_scheduling_history_retriever.py From bugbug with Mozilla Public License 2.0 | 5 votes |
def main(): description = "Retrieve and extract the test scheduling history from ActiveData" parser = argparse.ArgumentParser(description=description) parser.add_argument( "op", help="Which operation to perform.", choices=["retrieve", "generate"] ) parser.add_argument( "granularity", help="Which test granularity to use.", choices=["label", "group", "config_group"], ) parser.add_argument( "--reretrieve", type=int, default=0, help="How many results to reretrieve.", ) parser.add_argument( "--training-months", type=int, required=True, help="How many months of pushes to use for training.", ) args = parser.parse_args() retriever = Retriever() if args.op == "retrieve": retriever.generate_push_data( args.granularity, args.training_months, args.reretrieve ) elif args.op == "generate": retriever.generate_test_scheduling_history( args.granularity, args.training_months )
Example #6
Source File: commit_classifier.py From bugbug with Mozilla Public License 2.0 | 5 votes |
def main(): description = "Classify a commit" parser = argparse.ArgumentParser(description=description) parser.add_argument("model", help="Which model to use for evaluation") parser.add_argument( "repo_dir", help="Path to a Gecko repository. If no repository exists, it will be cloned to this location.", ) parser.add_argument( "--phabricator-deployment", help="Which Phabricator deployment to hit.", type=str, choices=[PHAB_PROD, PHAB_DEV], ) parser.add_argument("--diff-id", help="diff ID to analyze.", type=int) parser.add_argument("--revision", help="revision to analyze.", type=str) parser.add_argument( "--runnable-jobs", help="Path or URL to a file containing runnable jobs.", type=str, ) parser.add_argument( "--git_repo_dir", help="Path where the git repository will be cloned." ) parser.add_argument( "--method_defect_predictor_dir", help="Path where the git repository will be cloned.", ) args = parser.parse_args() classifier = CommitClassifier( args.model, args.repo_dir, args.git_repo_dir, args.method_defect_predictor_dir ) classifier.classify( args.revision, args.phabricator_deployment, args.diff_id, args.runnable_jobs )
Example #7
Source File: worldcup.py From worldcup with MIT License | 5 votes |
def main(): colorama.init() parser = argparse.ArgumentParser() parser.add_argument('endpoint', nargs='?', default='', help="Set a " +\ "filter on matches to retrieve (current, today, tomorrow)") parser.add_argument('-c', '--country', help="Filter matches to a " +\ "specific country code.") parser.add_argument('-g', '--group', help="Filter matches to a " +\ "specific group.") parser.add_argument('options', nargs='*', default='') args = parser.parse_args() endpoint = 'matches/' + args.endpoint if (args.country \ or args.endpoint.lower() == 'country' and len(args.options)): endpoint = 'matches/country?fifa_code=%(country)s' % { "country": args.country.upper() if args.country \ else args.options[0].upper() } elif (args.group or args.endpoint.lower() == 'group' and len(args.options)): endpoint = 'group_results' group_id = int(args.group or args.options[0]) for match in fetch(endpoint): if (match.get('group_id') == group_id): print(group_list(match)) return for match in fetch(endpoint): print(prettify(match))
Example #8
Source File: bug_retriever.py From bugbug with Mozilla Public License 2.0 | 5 votes |
def main(): description = "Retrieve and extract the information from Bugzilla instance" parser = argparse.ArgumentParser(description=description) parser.add_argument( "--limit", type=int, help="Only download the N oldest bugs, used mainly for integration tests", ) # Parse args to show the help if `--help` is passed args = parser.parse_args() retriever = Retriever() retriever.retrieve_bugs(args.limit)
Example #9
Source File: docker_gc.py From docker-custodian with Apache License 2.0 | 5 votes |
def get_args(args=None): parser = argparse.ArgumentParser() parser.add_argument( '--max-container-age', type=timedelta_type, help="Maximum age for a container. Containers older than this age " "will be removed. Age can be specified in any pytimeparse " "supported format.") parser.add_argument( '--max-image-age', type=timedelta_type, help="Maxium age for an image. Images older than this age will be " "removed. Age can be specified in any pytimeparse supported " "format.") parser.add_argument( '--dangling-volumes', action="store_true", help="Dangling volumes will be removed.") parser.add_argument( '--dry-run', action="store_true", help="Only log actions, don't remove anything.") parser.add_argument( '-t', '--timeout', type=int, default=60, help="HTTP timeout in seconds for making docker API calls.") parser.add_argument( '--exclude-image', action='append', help="Never remove images with this tag.") parser.add_argument( '--exclude-image-file', type=argparse.FileType('r'), help="Path to a file which contains a list of images to exclude, one " "image tag per line.") parser.add_argument( '--exclude-container-label', action='append', type=str, default=[], help="Never remove containers with this label key or label key=value") return parser.parse_args(args=args)
Example #10
Source File: GrafanaDatastoreServer.py From grafana-redistimeseries with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): global REDIS_POOL parser = argparse.ArgumentParser() parser.add_argument("--host", help="server address to listen to", default="0.0.0.0") parser.add_argument("--port", help="port number to listen to", default=8080, type=int) parser.add_argument("--redis-server", help="redis server address", default="localhost") parser.add_argument("--redis-port", help="redis server port", default=6379, type=int) args = parser.parse_args() REDIS_POOL = redis.ConnectionPool(host=args.redis_server, port=args.redis_port) http_server = WSGIServer(('', args.port), app) http_server.serve_forever()
Example #11
Source File: bidscoiner.py From bidscoin with GNU General Public License v3.0 | 5 votes |
def main(): """Console script usage""" # Parse the input arguments and run bidscoiner(args) import argparse import textwrap parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(__doc__), epilog='examples:\n' ' bidscoiner /project/foo/raw /project/foo/bids\n' ' bidscoiner -f /project/foo/raw /project/foo/bids -p sub-009 sub-030\n ') parser.add_argument('sourcefolder', help='The study root folder containing the raw data in sub-#/[ses-#/]data subfolders (or specify --subprefix and --sesprefix for different prefixes)') parser.add_argument('bidsfolder', help='The destination / output folder with the bids data') parser.add_argument('-p','--participant_label', help='Space separated list of selected sub-# names / folders to be processed (the sub- prefix can be removed). Otherwise all subjects in the sourcefolder will be selected', nargs='+') parser.add_argument('-f','--force', help='If this flag is given subjects will be processed, regardless of existing folders in the bidsfolder. Otherwise existing folders will be skipped', action='store_true') parser.add_argument('-s','--skip_participants', help='If this flag is given those subjects that are in participants.tsv will not be processed (also when the --force flag is given). Otherwise the participants.tsv table is ignored', action='store_true') parser.add_argument('-b','--bidsmap', help='The bidsmap YAML-file with the study heuristics. If the bidsmap filename is relative (i.e. no "/" in the name) then it is assumed to be located in bidsfolder/code/bidscoin. Default: bidsmap.yaml', default='bidsmap.yaml') parser.add_argument('-n','--subprefix', help="The prefix common for all the source subject-folders. Default: 'sub-'", default='sub-') parser.add_argument('-m','--sesprefix', help="The prefix common for all the source session-folders. Default: 'ses-'", default='ses-') parser.add_argument('-v','--version', help='Show the BIDS and BIDScoin version', action='version', version=f"BIDS-version:\t\t{bids.bidsversion()}\nBIDScoin-version:\t{bids.version()}") args = parser.parse_args() bidscoiner(rawfolder = args.sourcefolder, bidsfolder = args.bidsfolder, subjects = args.participant_label, force = args.force, participants = args.skip_participants, bidsmapfile = args.bidsmap, subprefix = args.subprefix, sesprefix = args.sesprefix)
Example #12
Source File: bulk_info.py From bulkvis with MIT License | 5 votes |
def get_args(): parser = ArgumentParser( description="""Given a directory containing bulk fast5 files output a CSV containing the run information for them""", formatter_class=ArgumentDefaultsHelpFormatter, add_help=False) general = parser.add_argument_group( title='General options') general.add_argument("-h", "--help", action="help", help="Show this help and exit" ) in_args = parser.add_argument_group( title='Input sources' ) in_args.add_argument("-d", "--dir", help="A directory containing bulk-fast5-files", type=str, required=True, metavar='' ) out_args = parser.add_argument_group( title='Output sources' ) out_args.add_argument("-o", "--out", help="Output csv filename", type=str, default='bulk_info.csv', required=True, metavar='' ) return parser.parse_args()
Example #13
Source File: stack_plot.py From git-of-theseus with Apache License 2.0 | 5 votes |
def stack_plot_cmdline(): parser = argparse.ArgumentParser(description='Plot stack plot') parser.add_argument('--display', action='store_true', help='Display plot') parser.add_argument('--outfile', default='stack_plot.png', type=str, help='Output file to store results (default: %(default)s)') parser.add_argument('--max-n', default=20, type=int, help='Max number of dataseries (will roll everything else into "other") (default: %(default)s)') parser.add_argument('--normalize', action='store_true', help='Normalize the plot to 100%%') parser.add_argument('--dont-stack', action='store_true', help='Don\'t stack plot') parser.add_argument('input_fn') kwargs = vars(parser.parse_args()) stack_plot(**kwargs)
Example #14
Source File: survival_plot.py From git-of-theseus with Apache License 2.0 | 5 votes |
def survival_plot_cmdline(): parser = argparse.ArgumentParser(description='Plot survival plot') parser.add_argument('--exp-fit', action='store_true', help='Plot exponential fit') parser.add_argument('--display', action='store_true', help='Display plot') parser.add_argument('--outfile', default='survival_plot.png', type=str, help='Output file to store results (default: %(default)s)') parser.add_argument('--years', type=float, default=5, help='Number of years on x axis (default: %(default)s)') parser.add_argument('input_fns', nargs='*') kwargs = vars(parser.parse_args()) survival_plot(**kwargs)
Example #15
Source File: gh2k.py From grimoirelab-elk with GNU General Public License v3.0 | 5 votes |
def get_params(): parser = get_params_parser() args = parser.parse_args() if not args.org or not args.token: parser.error("token and org params must be provided.") sys.exit(1) return args
Example #16
Source File: docker_autostop.py From docker-custodian with Apache License 2.0 | 5 votes |
def get_opts(args=None): parser = argparse.ArgumentParser() parser.add_argument( '--max-run-time', type=timedelta_type, help="Maximum time a container is allows to run. Time may " "be specified in any pytimeparse supported format." ) parser.add_argument( '--prefix', action="append", default=[], help="Only stop containers which match one of the " "prefix." ) parser.add_argument( '--dry-run', action="store_true", help="Only log actions, don't stop anything." ) parser.add_argument( '-t', '--timeout', type=int, default=60, help="HTTP timeout in seconds for making docker API calls." ) opts = parser.parse_args(args=args) if not opts.prefix: parser.error("Running with no --prefix will match nothing.") return opts
Example #17
Source File: nextaction.py From NextAction with MIT License | 5 votes |
def main(): parser = argparse.ArgumentParser(description='Add NextAction labels to Todoist.') parser.add_argument('--api_token', required=True, help='Your API key') parser.add_argument('--use_priority', required=False, action="store_true", help='Use priority 1 rather than a label to indicate the next actions.') global args args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) response = GetResponse(args.api_token) initial_data = response.read() logging.debug("Got initial data: %s", initial_data) initial_data = json.loads(initial_data) a = TodoistData(initial_data) while True: mods = a.GetProjectMods() if len(mods) == 0: time.sleep(5) else: logging.info("* Modifications necessary - skipping sleep cycle.") logging.info("** Beginning sync") sync_state = a.GetSyncState() changed_data = DoSyncAndGetUpdated(args.api_token,mods, sync_state).read() logging.debug("Got sync data %s", changed_data) changed_data = json.loads(changed_data) logging.info("* Updating model after receiving sync data") a.UpdateChangedData(changed_data) logging.info("* Finished updating model") logging.info("** Finished sync")
Example #18
Source File: autolabel.py From GitIssueBot with GNU Affero General Public License v3.0 | 5 votes |
def main(args=None): if args is None: # parse CLI arguments parser = argparser() args = parser.parse_args() # if only version is to be printed, do so and exit if args.version: print_version() # merge config (if given) and CLI parameters config = load_config(args.config) if args.token is not None: config["token"] = args.token if args.repo is not None: config["repo"] = args.repo if args.since is not None: config["since"] = args.since if args.mappings is not None: config["mappings"] = args.mappings config["ignore_case"] = config["ignore_case"] if "ignore_case" in config and config["ignore_case"] else False or args.ignore_case config["dryrun"] = config["dryrun"] if "dryrun" in config and config["dryrun"] else False or args.dryrun config["debug"] = config["debug"] if "debug" in config and config["debug"] else False or args.debug # validate the config validate_config(config) # setup logger setup_logging(debug=config["debug"]) # process existing issues try: process_issues(config, file=args.config, dryrun=config["dryrun"]) except: logger.exception("Error during execution") sys.exit(-1)
Example #19
Source File: fitnessd.py From anvil-course with MIT License | 5 votes |
def main(): auth.load_auth() parser = GooeyParser(description="Fitnessd local edition - record your health on the go!") if not auth.is_authorized(): parser.add_argument("Email", default=auth.email) parser.add_argument("Password", widget="PasswordField") parser.add_argument('Rate', help="Resting heart rate", type=int) parser.add_argument('Weight', help="Weight in pounds", type=int) parser.add_argument('Date', help="Date of measurement", widget="DateChooser", default=datetime.date.today()) data = parser.parse_args() rate = int(data.Rate) weight = int(data.Weight) recorded = dateutil.parser.parse(data.Date) if not auth.is_authorized(): email = data.Email password = data.Password api_key = svc.authenticate(email, password) if not api_key: print("Error authenticating") return else: print("Login successful") auth.save_auth(email, api_key) result = svc.save_measurement(auth.api_key, auth.email, rate, weight, recorded) if result: print("Done!") else: print("Error: Could not save measurement")
Example #20
Source File: cli.py From skil-python with Apache License 2.0 | 4 votes |
def command_dispatcher(self, args=None): desc = ( 'Pyskil - train, deploy and manage deep learning experiments with SKIL from Python.\n') parser = argparse.ArgumentParser(description=desc) parser.add_argument( '-v', '--version', action='version', version=pkg_resources.get_distribution("skil").version, help='Print pyskil version' ) subparsers = parser.add_subparsers(title='subcommands', dest='command') subparsers.add_parser( 'configure', help='Base configuration for pyskil. Run once') exp_parser = subparsers.add_parser( 'init-experiment', help='Initialize a SKIL experiment from scratch.') exp_parser.add_argument( '-f', '--file', help='File to persist the experiment to.') dep_parser = subparsers.add_parser( 'init-deployment', help='Initialize a SKIL deployment from scratch.') dep_parser.add_argument( '-f', '--file', help='File to persist the deployment to.') argcomplete.autocomplete(parser) args = parser.parse_args(args) self.var_args = vars(args) if not args.command: parser.print_help() return self.command = args.command if self.command == 'configure': self.configure() return if self.command == 'init-experiment': self.init_experiment(self.var_args['file']) return if self.command == 'init-deployment': self.init_deployment(self.var_args['file']) return
Example #21
Source File: utils.py From singer-python with Apache License 2.0 | 4 votes |
def parse_args(required_config_keys): '''Parse standard command-line args. Parses the command-line arguments mentioned in the SPEC and the BEST_PRACTICES documents: -c,--config Config file -s,--state State file -d,--discover Run in discover mode -p,--properties Properties file: DEPRECATED, please use --catalog instead --catalog Catalog file Returns the parsed args object from argparse. For each argument that point to JSON files (config, state, properties), we will automatically load and parse the JSON file. ''' parser = argparse.ArgumentParser() parser.add_argument( '-c', '--config', help='Config file', required=True) parser.add_argument( '-s', '--state', help='State file') parser.add_argument( '-p', '--properties', help='Property selections: DEPRECATED, Please use --catalog instead') parser.add_argument( '--catalog', help='Catalog file') parser.add_argument( '-d', '--discover', action='store_true', help='Do schema discovery') args = parser.parse_args() if args.config: setattr(args, 'config_path', args.config) args.config = load_json(args.config) if args.state: setattr(args, 'state_path', args.state) args.state = load_json(args.state) else: args.state = {} if args.properties: setattr(args, 'properties_path', args.properties) args.properties = load_json(args.properties) if args.catalog: setattr(args, 'catalog_path', args.catalog) args.catalog = Catalog.load(args.catalog) check_config(args.config, required_config_keys) return args
Example #22
Source File: tuptime-barchart.py From tuptime with GNU General Public License v2.0 | 4 votes |
def get_arguments(): """Get arguments from command line""" parser = argparse.ArgumentParser() parser.add_argument( '-b', '--bdate', dest='bdate', action='store', help='begin date to plot, format:"Y-m-d"', type=str ) parser.add_argument( '-e', '--edate', dest='edate', action='store', help='end date to plot, format:"Y-m-d" (default today)', type=str ) parser.add_argument( '-f', '--filedb', dest='dbfile', default=None, action='store', help='database file' ) parser.add_argument( '-H', '--height', dest='height', default=6, action='store', help='window height', type=int ) parser.add_argument( '-p', '--pastdays', dest='pdays', default=7, action='store', help='past days before edate to plot (default is 7)', type=int ) parser.add_argument( '-W', '--width', dest='width', default=8, action='store', help='window width', type=int ) arg = parser.parse_args() return arg
Example #23
Source File: twt_img.py From twitter-image-downloader with MIT License | 4 votes |
def main(): parser = argparse.ArgumentParser( description="Download all images uploaded by a specified Twitter user." ) parser.add_argument("user_id", help="Twitter user ID.") parser.add_argument( "-c", "--confidentials", help="A json file containing API keys." ) parser.add_argument( "-d", "--dest", help="Specify where to put images. " + 'If not specified, a directory named "user_name" will be created ' + "and images are saved to that directory.", default="", ) parser.add_argument( "-s", "--size", help="Specify the size of images.", default="large", choices=["large", "medium", "small", "thumb", "orig"], ) parser.add_argument( "-l", "--limit", type=int, help="The maximum number of tweets to check.", default=3200, ) parser.add_argument( "--rts", help="Save images contained in retweets.", action="store_true" ) args = parser.parse_args() if args.confidentials: with open(args.confidentials) as f: confidentials = json.loads(f.read()) if "api_key" not in confidentials or "api_secret" not in confidentials: raise e.ConfidentialsNotSuppliedError() api_key = confidentials["api_key"] api_secret = confidentials["api_secret"] else: raise e.ConfidentialsNotSuppliedError() user = args.user_id dest = args.dest if len(dest) == 0: if not os.path.exists(user): os.makedirs(user) dest = user downloader = Downloader(api_key, api_secret) downloader.download_images(user, dest, args.size, args.limit, args.rts)
Example #24
Source File: regressor_finder.py From bugbug with Mozilla Public License 2.0 | 4 votes |
def main() -> None: description = "Find bug-introducing commits from bug-fixing commits" parser = argparse.ArgumentParser(description=description) parser.add_argument("what", choices=["to_ignore", "bug_fixing", "bug_introducing"]) parser.add_argument( "--git_repo_url", help="URL to the git repository on which to run SZZ." ) parser.add_argument( "--git_repo_dir", help="Path where the git repository will be cloned." ) parser.add_argument( "--tokenized_git_repo_url", help="URL to the tokenized git repository on which to run SZZ.", ) parser.add_argument( "--tokenized_git_repo_dir", help="Path where the tokenized git repository will be cloned.", ) args = parser.parse_args() regressor_finder = RegressorFinder( args.git_repo_url, args.git_repo_dir, args.tokenized_git_repo_url, args.tokenized_git_repo_dir, ) if args.what == "to_ignore": regressor_finder.get_commits_to_ignore() elif args.what == "bug_fixing": regressor_finder.find_bug_fixing_commits() elif args.what == "bug_introducing": assert args.git_repo_url or args.tokenized_git_repo_url if args.git_repo_url: assert not args.tokenized_git_repo_url regressor_finder.find_bug_introducing_commits(args.git_repo_dir, False) evaluate(db.read(BUG_INTRODUCING_COMMITS_DB)) if args.tokenized_git_repo_url: assert not args.git_repo_url regressor_finder.find_bug_introducing_commits( args.tokenized_git_repo_dir, True ) evaluate(db.read(TOKENIZED_BUG_INTRODUCING_COMMITS_DB))
Example #25
Source File: cli.py From professional-services with Apache License 2.0 | 4 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument( '--admin-user', type=str, required=True, help='The GSuite Admin user email.') parser.add_argument( '--api', type=str, default='reports_v1', required=False, help='The GSuite Admin API.') parser.add_argument( '--applications', type=str, nargs='+', required=True, help='The GSuite Admin Applications.') parser.add_argument( '--project-id', type=str, required=True, help='The project id to export GSuite data to.') parser.add_argument( '--exporter', type=str, default='stackdriver_exporter.StackdriverExporter', required=False, help='The exporter class to use.') parser.add_argument( '--credentials-path', type=str, default=None, required=False, help='The service account credentials file.') parser.add_argument( '--offset', type=int, default=0, required=False, help='The offset to fetch logs from before the last sync (in minutes).') args = parser.parse_args() sync_all( args.admin_user, args.api, args.applications, args.project_id, args.exporter, args.credentials_path, args.offset)
Example #26
Source File: graphs.py From GarminDB with GNU General Public License v2.0 | 4 votes |
def main(argv): """Generate graphs based on commandline options.""" def date_from_string(date_string): return dateutil.parser.parse(date_string).date() parser = argparse.ArgumentParser() parser.add_argument("-v", "--version", help="print the program's version", action='version', version=format_version(sys.argv[0])) parser.add_argument("-t", "--trace", help="Turn on debug tracing", type=int, default=0) parser.add_argument("-S", "--save", help="Save graphs to images files.", action="store_true", default=False) # stat types to operate on stats_group = parser.add_argument_group('Statistics', 'Graph statistics over a period of time') stats_group.add_argument("-A", "--all", help="Graph data for all enabled statistics.", action='store_const', dest='stats', const=gc_config.enabled_stats(), default=[]) stats_group.add_argument("-m", "--monitoring", help="Graph monitoring data.", dest='stats', action='append_const', const=Statistics.monitoring) stats_group.add_argument("-r", "--hr", help="Graph heart rate data.", dest='stats', action='append_const', const=Statistics.rhr) stats_group.add_argument("-s", "--steps", help="Graph steps data.", dest='stats', action='append_const', const=Statistics.sleep) stats_group.add_argument("-w", "--weight", help="Graph weight data.", dest='stats', action='append_const', const=Statistics.weight) stats_group.add_argument("-p", "--period", help="Graph period granularity.", dest='period', type=str, default=None, choices=['days', 'weeks', 'months']) daily_group = parser.add_argument_group('Daily') daily_group.add_argument("-d", "--day", help="Graph composite data for a single day.", type=date_from_string) modifiers_group = parser.add_argument_group('Modifiers') modifiers_group.add_argument("-l", "--latest", help="Graph the latest data.", dest='days', type=int, default=None) args = parser.parse_args() if args.trace > 0: root_logger.setLevel(logging.DEBUG) else: root_logger.setLevel(logging.INFO) graph = Graph(args.trace, args.save) if Statistics.rhr in args.stats: graph.graph_activity('hr', args.period, args.days) if Statistics.itime in args.stats: graph.graph_activity('itime', args.period, args.days) if Statistics.steps in args.stats: graph.graph_activity('steps', args.period, args.days) if Statistics.weight in args.stats: graph.graph_activity('weight', args.period, args.days) if args.day: graph.graph_date(args.day)
Example #27
Source File: approve.py From GitIssueBot with GNU Affero General Public License v3.0 | 4 votes |
def main(args=None): if args is None: # parse CLI arguments parser = argparser() args = parser.parse_args() # if only version is to be printed, do so and exit if args.version: print_version() # merge config (if given) and CLI parameters config = load_config(args.config) if args.token is not None: config["token"] = args.token if args.repo is not None: config["repo"] = args.repo if args.since is not None: config["since"] = args.since if args.label is not None: config["label"] = args.label if args.oklabel is not None: config["oklabel"] = args.oklabel if args.ignored_labels is not None: config["ignored_labels"] = filter(lambda x: x is not None and len(x) > 0, map(str.strip, args.ignored_labels.split(","))) if args.ignored_titles is not None: config["ignored_titles"] = filter(lambda x: x is not None and len(x) > 0, map(str.strip, args.ignored_titles.split(","))) if args.grace_period is not None: config["grace_period"] = args.grace_period if args.phrase is not None: config["phrase"] = args.phrase if args.past_phrases is not None: config["past_phrases"] = filter(lambda x: x is not None and len(x) > 0, map(str.strip, args.past_phrases.split(","))) if args.reminder is not None: config["reminder"] = args.reminder if args.closing is not None: config["closing"] = args.closing if args.closingnow is not None: config["closingnow"] = args.closingnow config["close_directly"] = config["close_directly"] if "close_directly" in config and config["close_directly"] else False or args.close_directly config["dryrun"] = config["dryrun"] if "dryrun" in config and config["dryrun"] else False or args.dryrun config["debug"] = config["debug"] if "debug" in config and config["debug"] else False or args.debug # validate the config validate_config(config) # setup logger setup_logging(debug=config["debug"]) # check existing issues try: check_issues(config, file=args.config, dryrun=config["dryrun"]) except: logger.exception("Error during execution") sys.exit(-1)
Example #28
Source File: prcheck.py From GitIssueBot with GNU Affero General Public License v3.0 | 4 votes |
def main(args=None): if args is None: # parse CLI arguments parser = argparser() args = parser.parse_args() # if only version is to be printed, do so and exit if args.version: print_version() # merge config (if given) and CLI parameters config = load_config(args.config) if args.token is not None: config["token"] = args.token if args.repo is not None: config["repo"] = args.repo if args.since is not None: config["since"] = args.since if args.targets is not None: config["targets"] = args.targets if args.blacklisted_targets is not None: config["blacklisted_targets"] = args.blacklisted_targets if args.sources is not None: config["sources"] = args.sources if args.blacklisted_sources is not None: config["blacklisted_sources"] = args.blacklisted_sources config["title_compiled_regex"] = re.compile(config["title_regex"] if "title_regex" in config else '.*') config["ignore_case"] = config["ignore_case"] if "ignore_case" in config and config["ignore_case"] else False or args.ignore_case config["dryrun"] = config["dryrun"] if "dryrun" in config and config["dryrun"] else False or args.dryrun config["debug"] = config["debug"] if "debug" in config and config["debug"] else False or args.debug # validate the config validate_config(config) # setup logger setup_logging(debug=config["debug"]) # process existing issues try: process_prs(config, file=args.config, dryrun=config["dryrun"]) except: logger.exception("Error during execution") sys.exit(-1)
Example #29
Source File: __init__.py From pyphoon with MIT License | 4 votes |
def main(): """ Main entry point :param args: argparse.ArgumentParser object """ parser = argparse.ArgumentParser(description='Show Phase of the Moon') parser.add_argument( '-n', '--lines', help='Number of lines to display (size of the moon)', required=False, default=DEFAULTNUMLINES ) parser.add_argument( '-x', '--notext', help='Print no additional information, just the moon', required=False, default=DEFAULTNOTEXT, action="store_true" ) parser.add_argument( 'date', help='Date for that the phase of the Moon must be shown. Today by default', nargs='?', default=time.strftime("%Y-%m-%d %H:%M:%S") ) parser.add_argument( '-l', '--language', help='locale for that the phase of the Moon must be shown. English by default', nargs='?', default=None ) args = vars(parser.parse_args()) try: dateobj = time.mktime(dateutil.parser.parse(args['date']).timetuple()) except Exception as err: # pylint: disable=broad-except fatal(f"Can't parse date: {args['date']}") try: numlines = int(args['lines']) lang = args['language'] except Exception as err: # pylint: disable=broad-except print(err) fatal("Number of lines must be integer") try: notext = bool(args['notext']) except Exception as err: # pylint: disable=broad-except print(err) print(putmoon(dateobj, numlines, '@', notext, lang))
Example #30
Source File: get_activity.py From garminexport with Apache License 2.0 | 4 votes |
def main(): parser = argparse.ArgumentParser( description="Downloads one particular activity for a given Garmin Connect account.") # positional args parser.add_argument( "username", metavar="<username>", type=str, help="Account user name.") parser.add_argument( "activity", metavar="<activity>", type=int, help="Activity ID.") parser.add_argument( "format", metavar="<format>", type=str, help="Export format (one of: {}).".format(garminexport.backup.supported_export_formats)) # optional args parser.add_argument( "--password", type=str, help="Account password.") parser.add_argument( "--destination", metavar="DIR", type=str, help="Destination directory for downloaded activity. Default: ./activities/", default=os.path.join(".", "activities")) parser.add_argument( "--log-level", metavar="LEVEL", type=str, help="Desired log output level (DEBUG, INFO, WARNING, ERROR). Default: INFO.", default="INFO") args = parser.parse_args() if args.log_level not in LOG_LEVELS: raise ValueError("Illegal log-level argument: {}".format(args.log_level)) if args.format not in garminexport.backup.supported_export_formats: raise ValueError( "Unrecognized export format: '{}'. Must be one of {}".format( args.format, garminexport.backup.supported_export_formats)) logging.root.setLevel(LOG_LEVELS[args.log_level]) try: if not os.path.isdir(args.destination): os.makedirs(args.destination) if not args.password: args.password = getpass.getpass("Enter password: ") with GarminClient(args.username, args.password) as client: log.info("fetching activity %s ...", args.activity) summary = client.get_activity_summary(args.activity) # set up a retryer that will handle retries of failed activity downloads retryer = Retryer( delay_strategy=ExponentialBackoffDelayStrategy(initial_delay=timedelta(seconds=1)), stop_strategy=MaxRetriesStopStrategy(5)) start_time = dateutil.parser.parse(summary["summaryDTO"]["startTimeGMT"]) garminexport.backup.download( client, (args.activity, start_time), retryer, args.destination, export_formats=[args.format]) except Exception as e: log.error("failed with exception: %s", e) raise