示例#1
0
 def cmd_extract(self, argv):
   ''' Usage: {cmd} mobipath [outdir]
         Extract the contents of the MOBI file mobipath
         into the directory outdir, default based on the mobipath basename.
         Prints the outdir and the name of the top file.
   '''
   outdirpath = None
   if not argv:
     raise GetoptError("missing mobipath")
   mobipath = argv.pop(0)
   if argv:
     outdirpath = argv.pop(0)
   if argv:
     raise GetoptError("extra arguments after cbzpath: %r" % (argv,))
   if not existspath(mobipath):
     raise GetoptError("mobipath does not exist: %r" % (mobipath,))
   if outdirpath is None:
     outdirpath, mobiext = splitext(basename(mobipath))
   if existspath(outdirpath):
     raise GetoptError("outdir already exists: %s" % (outdirpath,))
   MB = Mobi(mobipath)
   extdirpath, rfilepath = MB.extract(outdirpath)
   assert extdirpath == outdirpath
   print(outdirpath)
   print(rfilepath)
示例#2
0
def get_args():
    """Returns program options as dictionary {'option': value}"""
    opts_dictionary = {}
    try:
        options, args = getopt(sys.argv[1:], '', 
                ['help', 'input=', 'output=', 'br', 'format='])

        if args: # args list is not empty
            raise GetoptError(
                'invalid program argument \'' + args[0] + '\'')
       
        opts_list = [opt[0] for opt in options]
        if len(opts_list) != len(set(opts_list)):
            raise GetoptError('cannot combine two or more same options')

        for arg in sys.argv[1:]:
            if (arg[2:] != 'help' and arg[2:] != 'br' and
                not re.match(r'\w+=.+', arg[2:])):
                raise GetoptError('bad option \'' + arg + '\'')
    except GetoptError as opt_error:
        error_print(sys.argv[0], ': ', end='', sep='')
        error_print(opt_error)
        sys.exit(exit_codes.BAD_ARGUMENTS)

    for opt in options:
        opts_dictionary[opt[0][2:]] = opt[1]
            
    return opts_dictionary
示例#3
0
def get_parameters(argv, needed_arguments, algorithms):
    opts = "a:"
    try:
        optlist, args = getopt(argv[1:], opts)
        optlist = dict(optlist)
    
        if "-a" not in optlist:
            requested_algorithms = sorted(algorithms.keys())
        else:
            if optlist["-a"].lower() not in algorithms:
                raise GetoptError("algorithm not found in : "+ " ".join(sorted(algorithms)))
            else:
                requested_algorithms = [optlist["-a"]]
    
    
        if len(args) < needed_arguments:
            raise GetoptError("Not enough arguments")
        else:
            inputs = list()
            for i in xrange(needed_arguments):
                try:
                    with open(args[i], "rb") as f:
                        inputs += [f.read()]
                except IOError:
                    inputs += [args[i]]
    
    except GetoptError, error:
        print("Error: %s\n" % error)
        #print(Help)
        exit()
示例#4
0
def main(argv):
    output = None
    style = 'oracle'
    optimizer = optimizers.get('none')              
    flags = 'vhfDSo:s:H:O:'
    keywords = [
        'help',
        'verbose',
        'output=',
        'style=',
        'header=',
        'optimizer=',
        'fast',
        'deferrable',
        'sort',
    ]
    try:                   
        opts, args = getopt(argv, flags, keywords)
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                usage()
                sys.exit(0)
            if opt in ('-v', '--verbose'):
                options['verbose'] = True
                continue
            if opt in ('-o', '--output'):
                output = arg
                continue
            if opt in ('-s', '--style'):
                if style in ('oracle', 'postgres'):
                    style = arg
                else:
                    raise GetoptError('style "%s, not-valid' % arg)
                continue
            if opt in ('-f', '--fast'):
                options['fast'] = 1
                continue
            if opt in ('-S', '--sort'):
                options['sort'] = True
                continue
            if opt in ('-O', '--optimizer'):
                optimizer = optimizers.get(arg)
                if optimizer is None:
                    raise GetoptError('optimizer "%s", not-valid' % arg)
                continue
            if opt in ('-H', '--header'):
                f = open(arg)
                options['header'] = f.read()
                f.close()
                continue
            if opt in ('-D', '--deferrable'):
                options['deferrable'] = True
                continue
        options['optimizer'] = optimizer
        processfiles(style, output, args)
    except GetoptError, e:
        print e
        usage()
        sys.exit(2)
def mkdir(tokens):
    global Remotedir
    cmd = 'mkdir'
    if len(tokens) == 1:
        raise GetoptError('')
    arg = Remotedir + tokens[1].strip()
    if not arg:
        raise GetoptError('')
    args = {'path': arg}
    return Task(no_return, cmd, args)
示例#6
0
 def cmd_attach(D, argv):
   ''' Attach an arbitrary Dirent to the current directory `D`.
       Usage: attach name dirent_spec
   '''
   if not D.isdir:
     raise GetoptError("not a Dir: %s" % (D,))
   if not argv:
     raise GetoptError("missing name")
   name = argv.pop()
   if not name or PATHSEP in name:
     raise GetoptError(
         "invalid name, may not be empty or contain the separator %r: %r" %
         (PATHSEP, name)
     )
   if not argv:
     raise GetoptError("missing dirent_spec")
   dirent_spec = argv.pop()
   if argv:
     raise GetoptError("extra arguments after dirent_spec: %r" % (argv,))
   try:
     E = parse(dirent_spec)
   except ValueError as e:
     raise GetoptError("parse failure: %r: %s" % (dirent_spec, e)) from e
   if not isinstance(E, _Dirent):
     raise GetoptError("not a Dirent specification: %r" % (dirent_spec,))
   if name in D:
     raise GetoptError("name already exists: %r" % (name,))
   D[name] = E
示例#7
0
 def cmd_ont(self, argv):
     ''' Usage: {cmd} type_name
 '''
     tagger = self.options.tagger
     if not argv:
         raise GetoptError("missing type_name")
     type_name = argv.pop(0)
     with Pfx("type %r", type_name):
         if argv:
             raise GetoptError("extra arguments: %r" % (argv, ))
     print(type_name)
     for type_value in tagger.ont_values(type_name):
         ontkey = f"{type_name}.{type_value}"
         with Pfx("ontkey = %r", ontkey):
             print(" ", r(type_value), tagger.ont[ontkey])
示例#8
0
 def cmd_ls(self, argv):
     ''' Usage: {cmd} [-l]
       List the contents of the Calibre library.
 '''
     long = False
     if argv and argv[0] == '-l':
         long = True
         argv.pop(0)
     if argv:
         raise GetoptError("extra arguments: %r" % (argv, ))
     options = self.options
     calibre = options.calibre
     for book in calibre:
         with Pfx("%d:%s", book.id, book.title):
             print(f"{book.title} ({book.dbid})")
             if long:
                 print(" ", book.path)
                 identifiers = book.identifiers_as_dict()
                 if identifiers:
                     print("   ", TagSet(identifiers))
                 for fmt, subpath in book.formats_as_dict().items():
                     with Pfx(fmt):
                         fspath = calibre.pathto(subpath)
                         size = pfx_call(os.stat, fspath).st_size
                         print("   ", fmt, transcribe_bytes_geek(size),
                               subpath)
示例#9
0
 def cmd_dbshell(self, argv):
     ''' Usage: {cmd}
       Start an interactive database prompt.
 '''
     if argv:
         raise GetoptError("extra arguments: %r" % (argv, ))
     return self.options.calibre.dbshell()
示例#10
0
def main(argv=None):
    ''' Main program: inspect or modify flags.
  '''
    if argv is None:
        argv = sys.argv
    else:
        argv = list(argv)
    cmd = argv.pop(0)
    usage = FLAG_USAGE % (cmd, cmd, cmd)
    xit = 0
    flagdir = None
    F = Flags(flagdir=flagdir)
    badopts = False
    try:
        if not argv:
            ks = sorted(F.keys())
            for k in ks:
                print(k, "TRUE" if F[k] else "FALSE")
        else:
            k = argv.pop(0)
            if not argv:
                xit = 0 if F[k] else 1
            else:
                value = argv.pop(0)
                if argv:
                    raise GetoptError("unexpected values after key value: %s" %
                                      (' '.join(argv), ))
                F[k] = truthy(value)
    except GetoptError as e:
        print("%s: warning: %s" % (cmd, e), file=sys.stderr)
        badopts = True
    if badopts:
        print(usage, file=sys.stderr)
        return 2
    return xit
示例#11
0
  def cmd_scan(self, args):
    ''' Scan a TVWiz directory.

        Usage: {cmd} recording...
          Scan the data structures of the supplied recordings.
    '''
    if not args:
      raise GetoptError("missing tvwizdirs")
    for tvwizdir in args:
      print(tvwizdir)
      total = 0
      chunkSize = 0
      chunkOff = 0
      for wizOffset, fileNum, flags, offset, size in TVWiz(tvwizdir
                                                           ).trunc_records():
        print("  wizOffset=%d, fileNum=%d, flags=%02x, offset=%d, size=%d" \
              % ( wizOffset, fileNum, flags, offset, size )
             )
        total += size
        if chunkOff != wizOffset:
          skip = wizOffset - chunkOff
          if chunkSize == 0:
            print("    %d skipped" % skip)
          else:
            print("    %d skipped, after a chunk of %d" % (skip, chunkSize))
          chunkOff = wizOffset
          chunkSize = 0
        chunkOff += size
        chunkSize += size
      if chunkOff > 0:
        print("    final chunk of %d" % chunkSize)
      print("  total %d" % total)
    return 0
示例#12
0
def main(argv):
    try:
        opts, args = getopt(argv, 'h', LONG_OPTIONS)
        length = 16
        if len(args) and args[0].isdigit():
            length = int(args[0])

        opt_list = []
        for opt, _ in opts:
            if opt == '-h':
                help()
                exit()
            else:
                opt_list.append(opt[2:])

        options = []
        for option in LONG_OPTIONS:
            if not option in opt_list:
                options.append(option[3:])

        if not len(options):
            raise GetoptError('Can\'t generate password with no char type')
    except GetoptError as err:
        print(err)
        help()
    except:
        print(exc_info())
        help()
    else:
        print(generate_password(length, options))
def account(tokens):
    cmd = 'account'
    args = {}
    start_pos = 0
    while start_pos < len(tokens):
        if '-' in tokens[start_pos]:
            break
        start_pos += 1
    if start_pos < len(tokens):
        opts, _ = getopt(tokens[start_pos:], 'n:p:a:',
                         ['name=', 'pwd=', 'auth='])
        tokens = tokens[:start_pos] + _
    else:
        opts = []
    if len(tokens) != 2:
        raise GetoptError('')
    args['action'] = tokens[1]
    for o, v in opts:
        if o in ('-n', '--name'):
            args['name'] = v
        elif o in ('-p', '--pwd'):
            args['pwd'] = v
        elif o in ('-a', '--auth'):
            args['auth'] = v
        else:
            raise GetoptError
    return Task(after_account, cmd, args)
示例#14
0
def parse_args(argv):
    try:
        opts, args = getopt(argv[1:], "udm:t:r:e:", ["usage","dryrun","rootdir=","exc_module=","inc_module=","inc_testcase="])

        opt_config = {} # optional flags
        
        for flag, value in opts:
            if flag in ("-m", "--inc_module"):
                opt_config[flag.replace("--","")] = value.split(",")
                continue
            elif flag in ("-t", "--inc_testcase"):
                opt_config[flag.replace("--","")] = value.split(",")
                continue
            elif flag in ("-e", "--exc_module"):
                opt_config[flag.replace("--","")] = value.split(",")
                continue
            elif flag in ("-r", "--rootdir"):
                pass
            elif flag in ("-d","--dryrun"):
                opt_config[flag.replace("--","")] = True
                continue
            elif flag in ("-u", "--usage"):
                usage()
                exit()
            else:
                assert GetoptError(flag + " unhandled option")
                
            opt_config[flag.replace("--","")] = value
                    
    except GetoptError as err:
        print err
        usage()
        sys.exit(2)
        
    return opt_config    
示例#15
0
 def cmd_toc(self, argv):
   ''' Usage: {cmd} [disc_id]
         Print a table of contents for the current disc.
   '''
   disc_id = None
   if argv:
     disc_id = argv.pop(0)
   if argv:
     raise GetoptError("extra arguments: %r" % (argv,))
   options = self.options
   MB = options.mbdb
   if disc_id is None:
     try:
       dev_info = discid.read(device=options.device)
     except discid.disc.DiscError as e:
       error("disc error: %s", e)
       return 1
     disc_id = dev_info.id
   with Pfx("discid %s", disc_id):
     disc = MB.discs[disc_id]
     print(disc.title)
     print(", ".join(disc.artist_names))
     for tracknum, recording in enumerate(disc.recordings(), 1):
       print(
           tracknum, recording.title, '--', ", ".join(recording.artist_names)
       )
   return 0
示例#16
0
 def cmd_stats(argv):
     ''' Usage: {cmd} host:port print [columns...]
       Fetch the statistics from the haproxy at host:port.
 '''
     badopts = False
     if not argv:
         warning("missing host:port")
         badopts = True
     else:
         host_port = argv.pop(0)
         with Pfx("host:port %r", host_port):
             try:
                 host, port = host_port.rsplit(':', 1)
                 port = int(port)
             except ValueError as e:
                 warning("invalid: %s", e)
                 badopts = True
     cols = argv
     if badopts:
         raise GetoptError("invalid arguments")
     S = Stats(host, port)
     for row in S.csvdata():
         if cols:
             print(*[getattr(row, col) for col in cols])
         else:
             print(*row)
def rm(tokens):
    global Remotedir
    cmd = 'delete'
    if len(tokens) != 2:
        raise GetoptError('')
    args = {'path': Remotedir + tokens[1]}
    return Task(no_return, cmd, args)
示例#18
0
 def cmd_rip(self, argv):
   ''' Usage: {cmd} [-n] [disc_id]
         Pull the audio into a subdirectory of the current directory.
         -n  No action; recite planned actions.
   '''
   options = self.options
   fstags = options.fstags
   dirpath = options.dirpath
   no_action = False
   disc_id = None
   if argv and argv[0] == '-n':
     no_action = True
     argv.pop(0)
   if argv:
     disc_id = argv.pop(0)
   if argv:
     raise GetoptError("extra arguments: %r" % (argv,))
   try:
     rip(
         options.device,
         options.mbdb,
         output_dirpath=dirpath,
         disc_id=disc_id,
         fstags=fstags,
         no_action=no_action,
     )
   except discid.disc.DiscError as e:
     error("disc error: %s", e)
     return 1
   return 0
示例#19
0
def getplugin(style):
    if style == 'oracle':
        from chameleon.oracle import Model as Oracle
        return Oracle()
    if style == 'postgres':
        from chameleon.postgres import Model as Postgres
        return Postgres()
    raise GetoptError('output style "%s" not supported' % style)
示例#20
0
 def cmd_tag(self, argv):
     xit = 0
     if not argv:
         raise GetoptError('missing book-title')
     book_title = argv.pop(0)
     with Pfx(book_title):
         for B in self.books_by_title(book_title):
             for tag_op in argv:
                 if tag_op.startswith('+'):
                     tag_name = tag_op[1:]
                     B.add_tag(tag_name)
                 elif tag_op.startswith('-'):
                     tag_name = tag_op[1:]
                     B.remove_tag(tag_name)
                 else:
                     raise GetoptError('unsupported tag op %r' % (tag_op, ))
     return xit
示例#21
0
def get_opts():
    opts = {'max-len': 8}
    options, args = getopt(sys.argv[1:], 't:ed')
    for key, value in options:
        opts[key.replace('-', '')] = value
    if 'e' in opts.keys() and 't' not in opts.keys():
        raise GetoptError('Error!! Please add -t in the righ of  -e!')
    return opts, args
示例#22
0
 def cmd_suspend(self, argv):
     ''' Usage: {cmd} vmname [VBoxManage controlvm options...]
       Suspend the specified VM using "controlvm .. savestate".
 '''
     if not argv:
         raise GetoptError("missing vmname")
     vmspec = argv.pop(0)
     return self.vbmg(['controlvm', vmspec, 'savestate'], argv)
示例#23
0
 def cmd_resume(self, argv):
     ''' Usage: {cmd} vmname [VBoxManage controlvm options...]
       Resume the specified VM using "controlvm .. resume".
 '''
     if not argv:
         raise GetoptError("missing vmname")
     vmspec = argv.pop(0)
     return self.vbmg(['controlvm', vmspec, 'resume'], argv)
示例#24
0
 def cmd_start(self, argv):
     ''' Usage: {cmd} vmname [VBoxManage startvm options...]
       Start the specified VM using "startvm".
 '''
     if not argv:
         raise GetoptError("missing vmname")
     vmspec = argv.pop(0)
     return self.vbmg(['startvm', vmspec], argv)
示例#25
0
def readArgs():
    try:
        opts, args = getopt(argv[1:], 'p:', ['process='])
        if len(opts) != 1:
            raise GetoptError("Entered a different number of options than 1")
    except GetoptError as error:
        print(error)
        exit(0)
    return opts[0][1]
示例#26
0
 def cmd_account(self, argv):
     ''' Usage: {cmd}
       Report account state.
 '''
     if argv:
         raise GetoptError("extra arguments: %r" % (argv, ))
     api = self.options.api
     for k, v in sorted(api.account().items()):
         print(k, pformat(v))
示例#27
0
 def cmd_gui(self, argv):
     ''' Usage: {cmd} pathnames...
       Run a GUI to tag pathnames.
 '''
     if not argv:
         raise GetoptError("missing pathnames")
     from .gui_tk import TaggerGUI  # pylint: disable=import-outside-toplevel
     with TaggerGUI(self.options.tagger, argv) as gui:
         gui.run()
def rename(tokens):
    global Remotedir
    cmd = 'rename'
    if len(tokens) != 3:
        raise GetoptError('')
    src = tokens[1]
    dst = tokens[2]
    args = {'path': Remotedir, 'src': src, 'dst': dst}
    return Task(no_return, cmd, args)
示例#29
0
def parse_args(argv):

    mandatory_flags = ['--access_type', '--input_filename']
    access_types = [
        'query', 'create', 'insert', 'table_exists', 'table_list',
        'table_info', 'database_exists'
    ]

    try:
        opts, args = getopt(argv[1:], "aiorf", ["access_type=", "input_filename=","output_filename=",\
                                                "runtime_path=","result_file="])
        for flag in mandatory_flags:
            if flag not in dict(opts).keys():
                raise GetoptError(flag, "needs to be present")

        man_config = {}  # mandatory flaags, hold the resulting, parsed flags
        opt_config = {}  # optional flags

        for flag, value in opts:
            if flag in ("-a", "--access_type"):
                if value not in access_types:
                    raise GetoptError(flag + " value not in " +
                                      str(access_types))
            elif flag in ("-i",
                          "--input_filename") or flag in ("-r",
                                                          "--runtime_path"):
                if os_file_exists(value) == False:
                    raise GetoptError(flag + "cannot find file" + value)
            elif flag in ("-f", "--result_file"):
                pass
            else:
                assert GetoptError(flag + " unhandled option")

            if flag in mandatory_flags:
                man_config[flag.replace("--", "")] = value
            else:
                opt_config[flag.replace("--", "")] = value

    except GetoptError as err:
        print err
        usage()
        sys.exit(2)

    return man_config, opt_config
示例#30
0
  def cmd_convert(self, args):
    ''' Convert a recording to MP4.

        Usage: {cmd} [start..end]... recording [output.mp4]
          Convert the video content of the named recording to
          the named output file (typically MP4, though the ffmpeg
          output format chosen is based on the extension).
          Most metadata are preserved.
          start..end: Optional start and end offsets in seconds, used
            to crop the recording output.
    '''
    badopts = False
    # parse optional start..end arguments
    timespans = []
    while args:
      range_arg = args[0]
      with Pfx("timespan %r", range_arg):
        try:
          start, end = range_arg.split('..')
          start_s = float(start)
          end_s = float(end)
        except ValueError:
          break
        else:
          args.pop(0)
          if start_s > end_s:
            warning("start:%s > end:%s", start, end)
            badopts = True
          timespans.append((start_s, end_s))
      if not args:
        raise GetoptError("missing recording")
      srcpath = args.pop(0)
      # collect optional dstpath
      if args:
        dstpath = args.pop(0)
      else:
        dstpath = None
      if args:
        warning("extra arguments: %s", ' '.join(args))
        badopts = True
      if badopts:
        raise GetoptError("bad invocation")
      R = Recording(srcpath)
      return 0 if R.convert(dstpath, max_n=TRY_N, timespans=timespans) else 1