Best Python code snippet using autotest_python
cmdline.py
Source:cmdline.py  
1# -*- coding: utf-8 -*-2"""3View for the Commandline UI4This module handles the main "sage-package" commandline utility, which5is also exposed as "sage --package".6"""7#*****************************************************************************8#       Copyright (C) 2016 Volker Braun <vbraun.name@gmail.com>9#10# This program is free software: you can redistribute it and/or modify11# it under the terms of the GNU General Public License as published by12# the Free Software Foundation, either version 2 of the License, or13# (at your option) any later version.14#                  http://www.gnu.org/licenses/15#*****************************************************************************16import os17import sys18import logging19log = logging.getLogger()20# Note that argparse is not part of Python 2.6, so we bundle it21try:22    import argparse23except ImportError:24    from sage_bootstrap.compat import argparse25from sage_bootstrap.app import Application26description = \27"""28Sage Bootstrap Library29"""30epilog = \31"""32The individual subcommands have their own detailed help, for example33run "sage --package config -h" to see the help on the config option.34"""35epilog_config = \36"""37Print the configuration38EXAMPLE:39    $ sage --package config40    Configuration:41    * log = info42    * interactive = True43"""44epilog_list = \45"""46Print a list of all available packages47EXAMPLE:48    $ sage --package list | sort49    4ti250    arb51    atlas52    autotools53    [...]54    zn_poly55"""56epilog_name = \57"""58Find the package name given a tarball filename59    60EXAMPLE:61    $ sage --package name pari-2.8-1564-gdeac36e.tar.gz62    pari63"""64epilog_tarball = \65"""66Find the tarball filename given a package name67    68EXAMPLE:69    $ sage --package tarball pari70    pari-2.8-1564-gdeac36e.tar.gz71"""72epilog_apropos = \73"""74Find up to 5 package names that are close to the given name75EXAMPLE:76    $ sage --package apropos python77    Did you mean: cython, ipython, python2, python3, patch?78"""79        80epilog_update = \81"""82Update a package. This modifies the Sage sources. 83    84EXAMPLE:85    $ sage --package update pari 2015 --url=http://localhost/pari/tarball.tgz86"""87epilog_download = \88"""89Download the tarball for a package and print the filename to stdout90    91EXAMPLE:92    $ sage --package download pari93    Using cached file /home/vbraun/Code/sage.git/upstream/pari-2.8-2044-g89b0f1e.tar.gz94    /home/vbraun/Code/sage.git/upstream/pari-2.8-2044-g89b0f1e.tar.gz95"""96epilog_fix_checksum = \97"""98Fix the checksum of a package99    100EXAMPLE:101    $ sage --package fix-checksum pari102    Updating checksum of pari-2.8-2044-g89b0f1e.tar.gz103"""104epilog_create = \105"""106Create new package, or overwrite existing package107    108EXAMPLE:109    $ sage --package create foo --version=3.14 --tarball=Foo-VERSION.tar.bz2 --type=standard110    Creating new package "foo"111"""112def make_parser():113    """114    The main commandline argument parser115    """116    parser = argparse.ArgumentParser(117        description=description, epilog=epilog,118        prog='sage --package',119        formatter_class=argparse.RawDescriptionHelpFormatter,120    )121    parser.add_argument('--log', dest='log', default=None,122                        help='one of [DEBUG, INFO, ERROR, WARNING, CRITICAL]')123    subparsers = parser.add_subparsers(dest='subcommand')124    parser_config = subparsers.add_parser(125        'config', epilog=epilog_config,126        formatter_class=argparse.RawDescriptionHelpFormatter,127        help='Print the configuration')128    parser_list = subparsers.add_parser(129        'list', epilog=epilog_list,130        formatter_class=argparse.RawDescriptionHelpFormatter,131        help='Print a list of all available packages')132    parser_name = subparsers.add_parser(133        'name', epilog=epilog_name,134        formatter_class=argparse.RawDescriptionHelpFormatter,135        help='Find the package name given a tarball filename')136    parser_name.add_argument('tarball_filename', type=str, help='Tarball filename')137    parser_tarball = subparsers.add_parser(138        'tarball', epilog=epilog_tarball,139        formatter_class=argparse.RawDescriptionHelpFormatter,140        help='Find the tarball filename given a package name')141    parser_tarball.add_argument('package_name', type=str, help='Package name')142    143    parser_apropos = subparsers.add_parser(144        'apropos', epilog=epilog_apropos,145        formatter_class=argparse.RawDescriptionHelpFormatter,146        help='Find up to 5 package names that are close to the given name')147    parser_apropos.add_argument(148        'incorrect_name', type=str, 149        help='Fuzzy name to search for')150    parser_update = subparsers.add_parser(151        'update', epilog=epilog_update,152        formatter_class=argparse.RawDescriptionHelpFormatter,153        help='Update a package. This modifies the Sage sources.')154    parser_update.add_argument(155        'package_name', type=str, help='Package name')156    parser_update.add_argument(157        'new_version', type=str, help='New version')158    parser_update.add_argument(159        '--url', type=str, default=None, help='Download URL')160    parser_download = subparsers.add_parser(161        'download', epilog=epilog_download,162        formatter_class=argparse.RawDescriptionHelpFormatter,163        help='Download tarball')164    parser_download.add_argument(165        'package_name', type=str, help='Package name')166    167    parser_fix_checksum = subparsers.add_parser(168        'fix-checksum', epilog=epilog_fix_checksum,169        formatter_class=argparse.RawDescriptionHelpFormatter,170        help='Fix the checksum of package.')171    parser_fix_checksum.add_argument(172        'package_name', nargs='?', default=None, type=str,173        help='Package name. Default: fix all packages.')174    175    parser_create = subparsers.add_parser(176        'create', epilog=epilog_create,177        formatter_class=argparse.RawDescriptionHelpFormatter,178        help='Create or overwrite package.')179    parser_create.add_argument(180        'package_name', nargs='?', default=None, type=str,181        help='Package name. Default: fix all packages.')182    parser_create.add_argument(183        '--version', type=str, default=None, help='Package version')184    parser_create.add_argument(185        '--tarball', type=str, default=None, help='Tarball filename pattern, e.g. Foo-VERSION.tar.bz2')186    parser_create.add_argument(187        '--type', type=str, default=None, help='Package type')188    return parser189def run():190    parser = make_parser()191    if len(sys.argv) == 1:192        parser.print_help()193        return194    args = parser.parse_args(sys.argv[1:])195    if args.log is not None:196        level = getattr(logging, args.log.upper())197        log.setLevel(level=level)198    log.debug('Commandline arguments: %s', args)199    app = Application()200    if args.subcommand == 'config':201        app.config()202    elif args.subcommand == 'list':203        app.list()204    elif args.subcommand == 'name':205        app.name(args.tarball_filename)206    elif args.subcommand == 'tarball':207        app.tarball(args.package_name)208    elif args.subcommand == 'apropos':209        app.apropos(args.incorrect_name)210    elif args.subcommand == 'update':211        app.update(args.package_name, args.new_version, url=args.url)212    elif args.subcommand == 'download':213        app.download(args.package_name)214    elif args.subcommand == 'create':215        app.create(args.package_name, args.version, args.tarball, args.type)216    elif args.subcommand == 'fix-checksum':217        if args.package_name is None:218            app.fix_all_checksums()219        else:220            app.fix_checksum(args.package_name)221    else:222        raise RuntimeError('unknown subcommand: {0}'.format(args))223        224if __name__ == '__main__':...simpletext_connector.py
Source:simpletext_connector.py  
1#!/usr/bin/env python2#3# Copyright 2007 Google Inc.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9#     http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17"""Bulkloader Simple Text writing.18Handle the simpletext format specified in a bulkloader.yaml file.19"""20from google.appengine.ext.bulkload import bulkloader_errors21from google.appengine.ext.bulkload import connector_interface22class SimpleTextConnector(connector_interface.ConnectorInterface):23  """Write a text file from dicts for each record. Does not support import."""24  VALID_MODES = ('text', 'nonewline', 'binary')25  @classmethod26  def create_from_options(cls, options, name):27    """Factory using an options dictionary.28    Args:29      options: Dictionary of options containing:30        template: A Python dict-interpolation string. Required.31        prolog: written before the per-record output.32        epilog: written after the per-record output.33        mode: one of the following, default is 'text'34          text: text file mode, newlines between records.35          nonewline: text file mode, no added newlines.36          binary: binary file mode, no added newlines.37      name: The name of this transformer, for use in error messages.38    Returns:39      SimpleTextConnector object described by the specified options.40    Raises:41      InvalidConfiguration: If the config is invalid.42    """43    template = options.get('template')44    if not template:45      raise bulkloader_errors.InvalidConfiguration(46          'simpletext must specify template. (In transformer named %s)' % name)47    prolog = options.get('prolog')48    epilog = options.get('epilog')49    mode = options.get('mode', 'text')50    return cls(template, prolog, epilog, mode, name)51  def __init__(self, template, prolog=None, epilog=None, mode='text', name=''):52    """Constructor.53    Args:54      template: A Python dict-interpolation string.55      prolog: written before the per-record output.56      epilog: written after the per-record output.57      mode: one of the following, default is 'text'58        text: text file mode, newlines between records.59        nonewline: text file mode, no added newlines.60        binary: binary file mode, no added newlines.61    """62    if mode not in self.VALID_MODES:63      raise bulkloader_errors.InvalidConfiguration(64          'simpletext mode must be one of "%s". (In transformer name %s.)' %65          ('", "'.join(self.VALID_MODES), name))66    self.template = template67    self.prolog = prolog68    self.epilog = epilog69    self.mode = mode70    self.export_file_pointer = None71  def initialize_export(self, filename, bulkload_state):72    """Open file and write prolog."""73    self.bulkload_state = bulkload_state74    mode = 'w'75    if self.mode == 'binary':76      mode = 'wb'77    self.export_file_pointer = open(filename, mode)78    if self.prolog:79      self.export_file_pointer.write(self.prolog)80      if self.mode == 'text':81        self.export_file_pointer.write('\n')82  def write_dict(self, dictionary):83    """Write one record for the specified entity."""84    self.export_file_pointer.write(self.template % dictionary)85    if self.mode == 'text':86      self.export_file_pointer.write('\n')87  def finalize_export(self):88    """Write epliog and close file after every record is written."""89    if self.epilog:90      self.export_file_pointer.write(self.epilog)91      if self.mode == 'text':92        self.export_file_pointer.write('\n')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
