def test_alias(): app = aaargh.App() @app.cmd(alias='foo2') def foo(): return 'foo-result' @app.cmd(alias=['bar1', 'bar2', b'bar3'.decode('ascii')]) def bar(): return 'bar-result' assert app.run(['foo']) == 'foo-result' assert app.run(['foo2']) == 'foo-result' assert app.run(['bar']) == 'bar-result' assert app.run(['bar1']) == 'bar-result' assert app.run(['bar2']) == 'bar-result' assert app.run(['bar3']) == 'bar-result'
def sample_app(): app = aaargh.App(description="A simple greeting application.") app.arg('-r', '--repeat', type=int, default=1, help="How many times?") @app.cmd def hello(repeat): # application level "repeat" argument is always passed return "Hello, world!" @app.cmd(name="hi", help="Say hi") # override subcommand name @app.cmd_arg('--name', '-n', default="stranger", help="Name of the person to greet") def say_hi(name, repeat): # both application and subcommand args out = [] for i in range(repeat): out.append("Hi, %s!" % name) return "\n".join(out) return app
import aaargh from boto import ec2 from boto.exception import EC2ResponseError from fabric.context_managers import settings, local_tunnel from fabric.api import run, sudo from fabric.contrib.files import upload_template, contains, append import time import docker from config import Config from utils import find app = aaargh.App(description="A prototype of skipper.") def get_or_create_security_group(c): groups = c.get_all_security_groups() group = find(groups, {'name': 'skipper'}) if not group: print("Creating new security group.") group = c.create_security_group("skipper", "Skipper security group") else: print("Found existing security group.") return group def authorize_group(group, ip_protocol, from_port, to_port, cidr_ip): """ Agruments: group: Security Group
import yaml from beefish import decrypt, encrypt_file import aaargh import grandfatherson from byteformat import ByteFormatter from bakthat.backends import GlacierBackend, S3Backend, RotationConfig, SwiftBackend from bakthat.conf import config, load_config, DEFAULT_DESTINATION, DEFAULT_LOCATION, CONFIG_FILE from bakthat.utils import _interval_string_to_seconds from bakthat.models import Backups from bakthat.sync import BakSyncer, bakmanager_hook, bakmanager_periodic_backups __version__ = "0.5.4" app = aaargh.App( description= "Compress, encrypt and upload files directly to Amazon S3/Glacier/Swift.") log = logging.getLogger(__name__) class BakthatFilter(logging.Filter): def filter(self, rec): if rec.name.startswith("bakthat") or rec.name == "root": return True else: return rec.levelno >= logging.WARNING STORAGE_BACKEND = dict(s3=S3Backend, glacier=GlacierBackend,
break except ImportError: pass from . import reader from . import v7conversion def gzip_wrap(fp): if fp.name.endswith('.gz'): return gzip.open(fp, mode='rt', encoding='ascii') else: return io.TextIOWrapper(fp, encoding='ascii') app = aaargh.App(description="Neustar (formerly Quova) data set utilities.") @app.cmd(help="Convert a Neustar V7 dataset to Whip format") @app.cmd_arg('input', type=argparse.FileType('rb'), nargs='?', default=sys.stdin, help="Input data file (defaults to stdin)") @app.cmd_arg('--date', help="Date to use (YYYY-MM-DD)") @app.cmd_arg('--output', '-o', default=sys.stdout, help="Output file (defaults to stdout)") def convert(input, date, output): if date is None:
import logging from time import time from sys import exit import aaargh import hedron import brainkey from sh import megals, megaput, megaget, megarm, ErrorReturnCode_1 logger = logging.getLogger(__name__) BV_PERSISTENCE_PATH = "/var/tmp/brainvault-persistence" BV_SUFFIX = '.tar.xz.ccrypt' BRAINVAULT_VERSIONED = BV_PERSISTENCE_PATH + "/{}-{}X" + BV_SUFFIX cli = aaargh.App() def brainvault_backup_path(brainvault_hashed, specific): hashed = brainkey.password_hash(brainvault_hashed, 'brainvault_persistence_filename') path = BRAINVAULT_VERSIONED.format(hashed, specific) return path @cli.cmd @cli.cmd_arg('brainvault_hashed') @cli.cmd_arg('--max_days', default=None, type=int) # --specific is without the X. FIXME: Should be in help output. @cli.cmd_arg('--specific', default=None, type=int) def locate_backup(brainvault_hashed, max_days=None, specific=None):
import colorama import os import subprocess import sys cfg = config.get_config() url = cfg.get('server', 'url').replace("://", "://%s:%s@" % (cfg.get('server', 'username'), cfg.get('server', 'password'))) + "dav/%s/" % (cfg.get('server', 'username'),) client = TaskDAVClient(url) cache_dir = cfg.get('cache', 'dir') if cfg.has_option('cache', 'dir') else None cache_update = cfg.get('cache', 'update') if cfg.has_option('cache', 'update') else None boolean_option = {'t': True, 'true': True, 'y': True, 'yes': True, 'f': False, 'false': False, 'n': False, 'no': False} cache_default = (boolean_option[cfg.get('cache', 'default').lower()] if cfg.has_option('cache', 'default') else True) if cache_dir else False utc = caldav.vobject.icalendar.utc app = aaargh.App(description="A simple command-line tool for interacting with Tasks over CalDAV") app.arg('-n', '--calendar-name', help="Name of the calendar to use", default="Tasks") app.arg('-c', '--color', dest='color', action="store_true", help="Color output mode", default=True) app.arg('-m', '--no-color', dest='color', action="store_false", help="Monochrome output mode (disable color)") def cache_args(f): """decorator that adds standard caching arguments to a cmd which reads data""" use_cache = app.cmd_arg('-C', '--cache', dest='use_cache', action="store_true", help="Use cache directory", default=None) no_use_cache = app.cmd_arg('--no-cache', dest='use_cache', action="store_false", help="Don't use cache directory") return no_use_cache(use_cache(f)) def cache_update_args(f): """decorator that adds standard caching arguments to a cmd which writes data, and does a background update after that command finishes""" use_cache = app.cmd_arg('-C', '--cache', dest='update_cache', action="store_true", help="Update cache directory after changes", default=None) no_use_cache = app.cmd_arg('--no-cache', dest='update_cache', action="store_false", help="Don't update cache directory after changes")
#!/usr/bin/env python __author__ = 'nitin' #Example: python dataupload.py gensql --datafile csvfile1.csv --dbtype MSSQL --outfile datascript1.sql --table Emp import aaargh import csv app = aaargh.App(description='CSV Data Uploader') @app.cmd @app.cmd_arg('--datafile', help='Path to the CSV file') @app.cmd_arg('--dbtype', help='Type of database', default='MSSQL') @app.cmd_arg('--outfile', help='Path to the output file', default='datascript.sql') @app.cmd_arg('--table', help='Type of database', default='Table1') def gensql(datafile, dbtype, outfile, table): if datafile is None: print('A datafile containing the input CSV must be specified') exit(-1) print('Datafile is %s, DB Type is %s, Outfile is %s' % (datafile, dbtype, outfile)) #print(datafile) def action_gensql(datafile, dbtype, outfile, table): with open(datafile, 'r') as fh: csvread = csv.reader(fh) is_first_row = True sqltxt = '' colnamecsv = '' colnamearr = None for row in csvread:
import sys import json import aaargh import urllib3 import requests import pyqrcode import simplejson from sshpubkeys import SSHKey urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning ) # Yes I know it's ugly. Please feel free to change it :) FC_URL = 'https://api.facelesscloud.com/api/' CLI_APP = aaargh.App() class Bcolors: """ Color Class """ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[32m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def convert_to_qrcode(str_to_convert):
logger = logging.getLogger(__name__) def lookup_and_print(db, ip, dt): value = db.lookup(ip, dt) if value is None: print("No hit found") return # Note: UltraJSON (ujson) does not support pretty printing, so use # built-in JSON module instead. parsed = json.loads(value.decode('UTF-8')) print(json.dumps(parsed, indent=2, sort_keys=True)) app = aaargh.App(description="Fast IP geo lookup") app.arg('--db', default='db', dest='db_dir') @app.cmd(name='load', help="Load data") @app.cmd_arg('inputs', type=argparse.FileType('rb'), nargs='+') def load_data(db_dir, inputs): logger.info("Importing %d data files: %r", len(inputs), ', '.join(x.name for x in inputs)) def gzip_wrap(fp): if fp.name.endswith('.gz'): return gzip.open(fp, mode='rt', encoding='UTF-8') else: return io.TextIOWrapper(fp, encoding='UTF-8')
from multiprocessing import Process from sys import argv from itertools import imap from butterfly import * from network import * import aaargh app = aaargh.App(description="`Distributed` computing of network usage") settings(port=39512, viewport=8123) net = Network() class ServeObserver: @property def progress(self): return float(len(self.complete)) / self.count_tasks def get(self): self.write("Hello!<br/>") self.write("Currently complete %.2f%%" % self.progress) class WorkerObserver: def get(self): self.write("Not implemented") @app.cmd @app.cmd_arg("-o",
from pulp_auto.qpid_handle import QpidHandle from pulp_auto.agent import Agent from pulp_auto.handler.profile import PROFILE from pulp_auto.consumer import Consumer from pulp_auto.pulp import Pulp from pulp_auto.authenticator import Authenticator import logging, sys, pulp_auto, time import aaargh import urllib3 from M2Crypto import (RSA, BIO) logging.basicConfig(level=logging.INFO) #level=logging.DEBUG) log = logging.getLogger(__file__) app = aaargh.App(description='Fake pulp consumer') @app.cmd(help='run the consumer') @app.cmd_arg('-u', '--url', help='URL of the AMQP broker to use', default='localhost') @app.cmd_arg('-n', '--consumer-name', help='consumer name to use', default='fake_consumer') @app.cmd_arg('-r', '--reporting', help='propagate errors back', default=False, action='store_true') @app.cmd_arg('-f', '--polling-frequency', help='polling frequency', type=float, default=3.0) @app.cmd_arg('-k', '--key-file', help='path to a key fille', default="") @app.cmd_arg('-p', '--pulp-url', help='pulp url to use', default="") @app.cmd_arg('-g', '--register', help='perform consumer registration', default=False, action='store_true') def run(url, consumer_name, reporting, polling_frequency, key_file, pulp_url, register): from gevent import monkey monkey.patch_all(select=False, thread=False) if not pulp_url:
import os try: import configparser except ImportError: # Python 3 import ConfigParser as configparser # NOQA import aaargh import prettytable from .events import (Events, TaskRunningError) from .i18n import (_, N_) from . import _version from . import utils APP = aaargh.App(description=__doc__.splitlines()[0].split("-", 1)[1], epilog=_("Please report bugs to [email protected]")) # pylint: disable-msg=R0903 class TaskAction(argparse.Action): """Define task name, handling --from-dir option.""" def __call__(self, parser, namespace, values, option_string=None): if namespace.task is True: namespace.task = os.path.basename(os.path.abspath(os.curdir)) else: namespace.task = values # pylint: enable-msg=R0903