This function is run inside the weirdo casapy IPython environment! A
    strange set of modules is available, and the
    `pwkit.environments.casa.scripting` system sets up a very particular
    environment to allow encapsulated scripting.
775282
def in_casapy (helper, asdm=None, ms=None):
    
    if asdm is None:
        raise ValueError ('asdm')
    if ms is None:
        raise ValueError ('ms')

    helper.casans.importasdm (
        asdm = asdm,
        vis = ms,
        asis = 'Antenna Station Receiver Source CalAtmosphere CalWVR CorrelatorMode SBSummary',
        bdfflags = True,
        lazy = False,
        process_caldevice = False,
    )
178376
function Module(options) {
    var module = this;
    options = options || {};

    /**
     * Whether the module is initialized.
     * @property {Boolean} [initialized=false]
     */
    module.initialized = false;
    /**
     * Whether the module is running.
     * @property {Boolean} [running=false]
     */
    module.running = false;

    ['init', 'start', 'stop', 'exit'].forEach(function(name) {
        var method = options[name];
        if (method) {
            var setMethod = 'set' + name[0].toUpperCase() + name.slice(1) + 'Method';
            module[setMethod](method);
        }
    });
}
276615
def run_script(scriptfile):
    ''''''
    try:
        f = open(scriptfile, mode='r')
    except Exception:
        return
    mpstate.console.writeln("Running script %s" % scriptfile)
    sub = mp_substitute.MAVSubstitute()
    for line in f:
        line = line.strip()
        if line == "" or line.startswith('#'):
            continue
        try:
            line = sub.substitute(line, os.environ)
        except mp_substitute.MAVSubstituteError as ex:
            print("Bad variable: %s" % str(ex))
            if mpstate.settings.script_fatal:
                sys.exit(1)
            continue
        if line.startswith('@'):
            line = line[1:]
        else:
            mpstate.console.writeln("-> %s" % line)
        process_stdin(line)
    f.close()
525241
def console_script():
    '''
        
    '''
    if len(sys.argv) == 1:
        print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]")
        return 0

    if "help" in sys.argv[1]:
        print("configcreate <server_url>:  Create initial config file for the OpenSubmit executor.")
        print("configtest:                 Check config file for correct installation of the OpenSubmit executor.")
        print("run:                        Fetch and run code to be tested from the OpenSubmit web server. Suitable for crontab.")
        print("test <dir>:                 Run test script from a local folder for testing purposes.")
        print("unlock:                     Break the script lock, because of crashed script.")
        print("help:                       Print this help")
        print(
            "-c config_file    Configuration file to be used (default: {0})".format(CONFIG_FILE_DEFAULT))
        return 0

    # Translate legacy commands
    if sys.argv[1] == "configure":
        sys.argv[1] = 'configtest'

    config_fname = get_config_fname(sys.argv)

    if "configcreate" in sys.argv[1]:
        print("Creating config file at " + config_fname)

        server_url = sys.argv[2]

        if create_config(config_fname, override_url=server_url):
            print("Config file created, fetching jobs from " + server_url)
            return 0
        else:
            return 1

    if "configtest" in sys.argv[1]:
        print("Testing config file at " + config_fname)

        if has_config(config_fname):
            config = read_config(config_fname)
            if not check_config(config):
                return 1
        else:
            print("ERROR: Seems like the config file %s does not exist. Call 'opensubmit-exec configcreate <server_url>' first." %
                  config_fname)
            return 1

        print("Sending host information update to server ...")
        send_hostinfo(config)
        return 0

    if "unlock" in sys.argv[1]:
        config = read_config(config_fname)
        break_lock(config)
        return 0

    if "run" in sys.argv[1]:
        config = read_config(config_fname)
        # Perform additional precautions for unattended mode in cron
        kill_longrunning(config)
        with ScriptLock(config):
            download_and_run(config)
        return 0

    if "test" in sys.argv[1]:
        config = read_config(config_fname)
        copy_and_run(config, sys.argv[2])
        return 0
131044
def _module_env(self, execution):
        
        env = copy.copy(os.environ)
        try:
            for mod in execution.get('modules') or []:
                Module.load(mod)
            os.environ.update(execution.get('environment') or {})
            yield
        finally:
            os.environ = env
672050
def _setup_py_run_from_dir(root_dir, py_interpreter):
    """"""
    data = {}
    with _enter_single_subdir(root_dir) as single_subdir:
        if not os.path.exists("setup.py"):
            raise Exception("'setup.py' does not exist in '%s'" % (
                single_subdir))
        # generate a temporary json file which contains the metadata
        output_json = tempfile.NamedTemporaryFile()
        cmd = "%s setup.py -q --command-packages metaextract " \
              "metaextract -o %s " % (py_interpreter, output_json.name)
        try:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        except subprocess.CalledProcessError:
            # try again with a encoding in setup.py
            _set_file_encoding_utf8("setup.py")
            subprocess.check_output(cmd, shell=True)

        # read json file and return data
        with open(output_json.name, "r") as f:
            data = json.loads(f.read())

        # sort some of the keys if the dict values are lists
        for key in ['data_files', 'entry_points', 'extras_require',
                    'install_requires', 'setup_requires', 'scripts',
                    'tests_require', 'tests_suite']:
            if key in data['data'] and isinstance(data['data'][key], list):
                data['data'][key] = sorted(data['data'][key])
    return data
1351361
function getPythonExecutable(options, platform) {
    if (options.virtualenv) {
      var isWin = /^win/.test(platform);
      var pythonExec = isWin ?
        path.join(options.virtualenv, 'Scripts', 'python.exe') :
        path.join(options.virtualenv, 'bin', 'python');
      delete options.virtualenv;
      return pythonExec;
    } else {
      return 'python';
    }
  }
1025553
def console_script(fsroot=''):
    '''
        
    '''

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Administration for the OpenSubmit web application.')
    parser.add_argument('-c', '--config', default='/etc/opensubmit/settings.ini', help='OpenSubmit configuration file.')
    subparsers = parser.add_subparsers(dest='command', help='Supported administrative actions.')
    parser_configcreate = subparsers.add_parser('configcreate', help='Create initial config files for the OpenSubmit web server.')
    parser_configcreate.add_argument('--debug', default=is_str_true(os.environ.get('OPENSUBMIT_DEBUG', 'False')), action='store_true', help='Enable debug mode, not for production systems.')
    parser_configcreate.add_argument('--server_url', default=os.environ.get('OPENSUBMIT_SERVER_URL', 'http://localhost:8000'), help='The main URL of the OpenSubmit installation, including sub-directories.')
    parser_configcreate.add_argument('--server_mediaroot', default=os.environ.get('OPENSUBMIT_SERVER_MEDIAROOT', '/tmp/'), help='Storage path for uploadeded files.')
    parser_configcreate.add_argument('--server_hostaliases', default=os.environ.get('OPENSUBMIT_SERVER_HOSTALIASES', '127.0.0.1'), help='Comma-separated list of alternative host names for the web server.')
    parser_configcreate.add_argument('--server_logfile', default=os.environ.get('OPENSUBMIT_SERVER_LOGFILE', '/tmp/opensubmit.log'), help='Log file for the OpenSubmit application.')
    parser_configcreate.add_argument('--server_timezone', default=os.environ.get('OPENSUBMIT_SERVER_TIMEZONE', 'Europe/Berlin'), help='Time zone for all dates and deadlines.')
    parser_configcreate.add_argument('--database_name', default=os.environ.get('OPENSUBMIT_DATABASE_NAME', '/tmp/database.sqlite'), help='Name of the database (file).'),
    parser_configcreate.add_argument('--database_engine', default=os.environ.get('OPENSUBMIT_DATABASE_ENGINE', 'sqlite3'), choices=['postgresql', 'mysql', 'sqlite3', 'oracle'])
    parser_configcreate.add_argument('--database_user', default=os.environ.get('OPENSUBMIT_DATABASE_USER', ''), help='The user name for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--database_password', default=os.environ.get('OPENSUBMIT_DATABASE_PASSWORD', ''), help='The user password for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--database_host', default=os.environ.get('OPENSUBMIT_DATABASE_HOST', ''), help='The host name for accessing the database. Not needed for SQLite. Default is localhost.')
    parser_configcreate.add_argument('--database_port', default=os.environ.get('OPENSUBMIT_DATABASE_PORT', ''), help='The port number for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--login_google_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GOOGLE_OAUTH_KEY', ''), help='Google OAuth client key.')
    parser_configcreate.add_argument('--login_google_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GOOGLE_OAUTH_SECRET', ''), help='Google OAuth client secret.')
    parser_configcreate.add_argument('--login_twitter_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_TWITTER_OAUTH_KEY', ''), help='Twitter OAuth client key.')
    parser_configcreate.add_argument('--login_twitter_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_TWITTER_OAUTH_SECRET', ''), help='Twitter OAuth client secret.')
    parser_configcreate.add_argument('--login_github_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GITHUB_OAUTH_KEY', ''), help='GitHub OAuth client key.')
    parser_configcreate.add_argument('--login_github_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GITHUB_OAUTH_SECRET', ''), help='GitHUb OAuth client secret.')
    parser_configcreate.add_argument('--login_gitlab_description', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_DESCRIPTION', ''), help='Title of the GitLab login button.')
    parser_configcreate.add_argument('--login_gitlab_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_OAUTH_KEY', ''), help='GitLab OAuth client key.')
    parser_configcreate.add_argument('--login_gitlab_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_OAUTH_SECRET', ''), help='GitLab OAuth client secret.')
    parser_configcreate.add_argument('--login_gitlab_url', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_URL', ''), help='GitLab URL.')
    parser_configcreate.add_argument('--login_openid_description', default=os.environ.get('OPENSUBMIT_LOGIN_OPENID_DESCRIPTION', 'StackExchange'), help='Title of the OpenID login button.')
    parser_configcreate.add_argument('--login_openid_provider', default=os.environ.get('OPENSUBMIT_LOGIN_OPENID_PROVIDER', 'https://openid.stackexchange.com'), help='URL of the OpenID provider.')
    parser_configcreate.add_argument('--login_oidc_description', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_DESCRIPTION', ''), help='Title of the OpenID Connect login button.')
    parser_configcreate.add_argument('--login_oidc_endpoint', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_ENDPOINT', ''), help='URL of the OpenID Connect endpoint.')
    parser_configcreate.add_argument('--login_oidc_client_id', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_CLIENT_ID', ''), help='OpenID Connect client id.')
    parser_configcreate.add_argument('--login_oidc_client_secret', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_CLIENT_SECRET', ''), help='OpenID Connect client secret.')
    parser_configcreate.add_argument('--login_shib_description', default=os.environ.get('OPENSUBMIT_LOGIN_SHIB_DESCRIPTION', ''), help='Title of the Shibboleth login button.')
    parser_configcreate.add_argument('--login_demo', default=is_str_true(os.environ.get('OPENSUBMIT_LOGIN_DEMO', 'False')), action='store_true', help='Offer demo login options.')
    parser_configcreate.add_argument('--admin_name', default=os.environ.get('OPENSUBMIT_ADMIN_NAME', 'OpenSubmit Administrator'), help='Name of the administrator, shown in privacy policy, impress and backend.')
    parser_configcreate.add_argument('--admin_email', default=os.environ.get('OPENSUBMIT_ADMIN_EMAIL', 'root@localhost'), help='eMail of the administrator, shown in privacy policy, impress and backend.')
    parser_configcreate.add_argument('--admin_address', default=os.environ.get('OPENSUBMIT_ADMIN_ADDRESS', '(address available by eMail)'), help='Address of the administrator, shown in privacy policy and impress.')
    parser_configcreate.add_argument('--admin_impress_page', default=os.environ.get('OPENSUBMIT_IMPRESS_PAGE', ''), help='Link to alternative impress page.')
    parser_configcreate.add_argument('--admin_privacy_page', default=os.environ.get('OPENSUBMIT_PRIVACY_PAGE', ''), help='Link to alternative privacy policy page.')
    parser_configcreate.add_argument('--whitelist_openid', default=os.environ.get('OPENSUBMIT_WHITELIST_OPENID', ''), help='Comma-separated list of allowed email addresses for OpenID login.')
    parser_configcreate.add_argument('--whitelist_twitter', default=os.environ.get('OPENSUBMIT_WHITELIST_TWITTER', ''), help='Comma-separated list of allowed email addresses for Twitter login.')
    parser_configcreate.add_argument('--whitelist_google', default=os.environ.get('OPENSUBMIT_WHITELIST_GOOGLE', ''), help='Comma-separated list of allowed email addresses for Google login.')
    parser_configcreate.add_argument('--whitelist_github', default=os.environ.get('OPENSUBMIT_WHITELIST_GITHUB', ''), help='Comma-separated list of allowed email addresses for GitHub login.')
    parser_configcreate.add_argument('--whitelist_gitlab', default=os.environ.get('OPENSUBMIT_WHITELIST_GITLAB', ''), help='Comma-separated list of allowed email addresses for GitLab login.')
    parser_configcreate.add_argument('--whitelist_oidc', default=os.environ.get('OPENSUBMIT_WHITELIST_OIDC', ''), help='Comma-separated list of allowed email addresses for OpenID connect login.')
    parser_configcreate.add_argument('--whitelist_shib', default=os.environ.get('OPENSUBMIT_WHITELIST_SHIB', ''), help='Comma-separated list of allowed email addresses for Shibboleth login.')

    subparsers.add_parser('configtest', aliases=['configure'], help='Check config files and database for correct installation of the OpenSubmit web server.')
    subparsers.add_parser('democreate', aliases=['createdemo'], help='Install some test data (courses, assignments, users).')
    subparsers.add_parser('apachecreate', help='Create config file snippet for Apache 2.4.')
    subparsers.add_parser('fixperms', help='Check and fix student and tutor permissions.')
    subparsers.add_parser('configdump', aliases=['dumpconfig'], help='Show effective OpenSubmit configuration at run-time.')
    subparsers.add_parser('fixchecksums', help='Re-create all student file checksums (for duplicate detection).')

    parser_makeadmin = subparsers.add_parser('makeadmin', help='Make this user an admin with backend rights.')
    parser_makeadmin.add_argument('email')
    parser_makeowner = subparsers.add_parser('makeowner', help='Make this user a course owner with backend rights.')
    parser_makeowner.add_argument('email')
    parser_maketutor = subparsers.add_parser('maketutor', help='Make this user a course tutor with backend rights.')
    parser_maketutor.add_argument('email')
    parser_makestudent = subparsers.add_parser('makestudent', help='Make this user a student without backend rights.')
    parser_makestudent.add_argument('email')
    args = parser.parse_args()

    config_file = fsroot + args.config

    if args.command == 'apachecreate':
        config = check_web_config(config_file)
        if config:
            apache_config(config, os.path.dirname(config_file) + os.sep + 'apache24.conf')
        return

    if args.command == 'configcreate':
        configcreate(config_file, vars(args))
        return

    if args.command == 'configtest':
        configtest(config_file)
        return

    if args.command in ['fixperms', 'fixchecksums', 'democreate', 'createdemo', 'dumpconfig', 'configdump']:
        django_admin([args.command])
        return

    if args.command in ['makeadmin', 'makeowner', 'maketutor', 'makestudent']:
        django_admin([args.command, args.email])
        return
593079
def hook(module):
    
    if "INSTANA_DEV" in os.environ:
        print("==============================================================")
        print("Instana: Running flask hook")
        print("==============================================================")
    wrapt.wrap_function_wrapper('flask', 'Flask.__init__', wrapper)
92710
function runScripts() {
  var scripts = [];
  var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
  var index = 0;

  /**
   * Transform and execute script. Ensures correct load order.
   */

  var exec = function exec() {
    var param = scripts[index];
    if (param instanceof Array) {
      transform.run.apply(transform, param);
      index++;
      exec();
    }
  };

  /**
   * Load, transform, and execute all scripts.
   */

  var run = function run(script, i) {
    var opts = {};

    if (script.src) {
      transform.load(script.src, function (param) {
        scripts[i] = param;
        exec();
      }, opts, true);
    } else {
      opts.filename = "embedded";
      scripts[i] = [script.innerHTML, opts];
    }
  };

  // Collect scripts with Babel `types`.

  var _scripts = global.document.getElementsByTagName("script");

  for (var i = 0; i < _scripts.length; ++i) {
    var _script = _scripts[i];
    if (types.indexOf(_script.type) >= 0) scripts.push(_script);
  }

  for (i in scripts) {
    run(scripts[i], i);
  }

  exec();
}
987740
def setup(basepath=DEFAULT_BASEPATH):
    """"""

    module_version = os.environ.get('MODULE_VERSION', DEFAULT_VERSION)
    moduleshome = os.path.join(basepath, module_version)

    # Abort if MODULESHOME does not exist
    if not os.path.isdir(moduleshome):
        print('payu: warning: MODULESHOME does not exist; disabling '
              'environment modules.')
        os.environ['MODULESHOME'] = ''
        return

    os.environ['MODULE_VERSION'] = module_version
    os.environ['MODULE_VERSION_STACK'] = module_version
    os.environ['MODULESHOME'] = moduleshome

    if 'MODULEPATH' not in os.environ:
        module_initpath = os.path.join(moduleshome, 'init', '.modulespath')
        with open(module_initpath) as initpaths:
            modpaths = [
                line.partition('#')[0].strip()
                for line in initpaths.readlines() if not line.startswith('#')
            ]

        os.environ['MODULEPATH'] = ':'.join(modpaths)

    os.environ['LOADEDMODULES'] = os.environ.get('LOADEDMODULES', '')

    # Environment modules with certain characters will cause corruption
    # when MPI jobs get launched on other nodes (possibly a PBS issue).
    #
    # Bash processes obscure the issue on Raijin, since it occurs in an
    # environment module function, and bash moves those to the end of
    # the environment variable list.
    #
    # Raijin's mpirun wrapper is a bash script, and therefore "fixes" by doing
    # the shuffle and limiting the damage to other bash functions, but some
    # wrappers (e.g. OpenMPI 2.1.x) may not be present.  So we manually patch
    # the problematic variable here.  But a more general solution would be nice
    # someday.

    if 'BASH_FUNC_module()' in os.environ:
        bash_func_module = os.environ['BASH_FUNC_module()']
        os.environ['BASH_FUNC_module()'] = bash_func_module.replace('\n', ';')
1282731
def add(entry_point, all_entry_points, auto_write, scripts_path):
    ''''''

    click.echo()
    if not entry_point and not all_entry_points:
        raise click.UsageError(
            'Missing required option: --entry_point or --all_entry_points'
        )
    if not os.path.exists('setup.py'):
        raise click.UsageError('No setup.py found.')

    setup_data = parse_setup('setup.py')
    console_scripts = get_console_scripts(setup_data)

    scripts = []
    if all_entry_points and console_scripts:

        # Make sure our entry points start with py
        for entry in console_scripts:
            if not entry.startswith('py'):
                click.echo('Your python entry_points must start with py.')
                click.echo('Found: ' + entry)
                raise click.Abort()

        for entry in console_scripts:
            click.echo('Found entry_point: ' + entry)
            py_entry_point = entry
            entry_point = entry[2:]
            more_scripts = copy_templates(
                entry_point,
                py_entry_point,
                auto_write,
                scripts_path
            )

            for script in more_scripts:
                click.echo('    Created ' + script)

            scripts.extend(more_scripts)

    elif entry_point:
        if not entry_point.startswith('py'):
            click.echo('Your python entry_points must start with py.')
            raise click.Abort()
        if entry_point not in console_scripts:
            click.echo(entry_point + ' not found in your setups entry_points')
            click.echo('You will need to add it afterward if you continue...')
            click.echo('')
            click.confirm('Do you want to continue?', abort=True)

        click.echo('\nCreating scripts for: ' + entry_point)
        py_entry_point = entry_point
        entry_point = entry_point[2:]
        more_scripts = copy_templates(
            entry_point,
            py_entry_point,
            auto_write,
            scripts_path
        )

        for script in more_scripts:
            click.echo('    Created ' + script)

        scripts.extend(more_scripts)

    click.echo('\n\nAdd the following section to your package setup:\n')
    click.echo('scripts=[')
    for script in scripts:
        click.echo("    '{}',".format(script))
    click.echo('],')
816265
function runScriptViaChildProcessSpawn(script, context) {
    var opts = context.opts;
    var command = script.fullPath;
    var args = [opts.projectRoot];

    if (fs.statSync(script.fullPath).isDirectory()) {
        events.emit('verbose', 'Skipped directory "' + script.fullPath + '" within hook directory');
        return Q();
    }

    if (isWindows) {
        // TODO: Make shebang sniffing a setting (not everyone will want this).
        var interpreter = extractSheBangInterpreter(script.fullPath);
        // we have shebang, so try to run this script using correct interpreter
        if (interpreter) {
            args.unshift(command);
            command = interpreter;
        }
    }

    var execOpts = {cwd: opts.projectRoot, printCommand: true, stdio: 'inherit'};
    execOpts.env = {};
    execOpts.env.CORDOVA_VERSION = require('../../package').version;
    execOpts.env.CORDOVA_PLATFORMS = opts.platforms ? opts.platforms.join() : '';
    execOpts.env.CORDOVA_PLUGINS = opts.plugins ? opts.plugins.join() : '';
    execOpts.env.CORDOVA_HOOK = script.fullPath;
    execOpts.env.CORDOVA_CMDLINE = process.argv.join(' ');

    return superspawn.spawn(command, args, execOpts)
        .catch(function(err) {
            // Don't treat non-executable files as errors. They could be READMEs, or Windows-only scripts.
            if (!isWindows && err.code == 'EACCES') {
                events.emit('verbose', 'Skipped non-executable file: ' + script.fullPath);
            } else {
                throw new Error('Hook failed with error code ' + err.code + ': ' + script.fullPath);
            }
        });
}
540977
def in_notebook():
    
    try:
        # function returns IPython context, but only in IPython
        ipy = get_ipython()  # NOQA
        # we only want to render rich output in notebooks
        # in terminals we definitely do not want to output HTML
        name = str(ipy.__class__).lower()
        terminal = 'terminal' in name

        # spyder uses ZMQshell, and can appear to be a notebook
        spyder = '_' in os.environ and 'spyder' in os.environ['_']

        # assume we are in a notebook if we are not in
        # a terminal and we haven't been run by spyder
        notebook = (not terminal) and (not spyder)

        return notebook

    except BaseException:
        return False
163083
def build_module(project, env=None):
        ''''''
        from pyspider.libs import base_handler
        assert 'name' in project, 'need name of project'
        assert 'script' in project, 'need script of project'

        if env is None:
            env = {}
        # fix for old non-package version scripts
        pyspider_path = os.path.join(os.path.dirname(__file__), "..")
        if pyspider_path not in sys.path:
            sys.path.insert(1, pyspider_path)

        env = dict(env)
        env.update({
            'debug': project.get('status', 'DEBUG') == 'DEBUG',
        })

        loader = ProjectLoader(project)
        module = loader.load_module(project['name'])

        # logger inject
        module.log_buffer = []
        module.logging = module.logger = logging.Logger(project['name'])
        if env.get('enable_stdout_capture', True):
            handler = SaveLogHandler(module.log_buffer)
            handler.setFormatter(LogFormatter(color=False))
        else:
            handler = logging.StreamHandler()
            handler.setFormatter(LogFormatter(color=True))
        module.logger.addHandler(handler)

        if '__handler_cls__' not in module.__dict__:
            BaseHandler = module.__dict__.get('BaseHandler', base_handler.BaseHandler)
            for each in list(six.itervalues(module.__dict__)):
                if inspect.isclass(each) and each is not BaseHandler \
                        and issubclass(each, BaseHandler):
                    module.__dict__['__handler_cls__'] = each
        _class = module.__dict__.get('__handler_cls__')
        assert _class is not None, "need BaseHandler in project module"

        instance = _class()
        instance.__env__ = env
        instance.project_name = project['name']
        instance.project = project

        return {
            'loader': loader,
            'module': module,
            'class': _class,
            'instance': instance,
            'exception': None,
            'exception_log': '',
            'info': project,
            'load_time': time.time(),
        }
9457
def other_dependancies(server, environment):
    
    print('  ** Other Dependancides, based on server', server, '**')
    server = server.lower()
    # Pillow is not on TestPyPI
    if server is "local":
        pass
    elif server in ["testpypi", "pypitest"]:
        # these are packages not available on the test server, so install them
        # off the regular pypi server
        print("  **Install Pillow**")
        subprocess.call([environment + '\\Scripts\\pip.exe', 'install', 'Pillow'], shell=True)
    elif server in ["pypi"]:
        print("  **Install Pillow**")
        subprocess.call([environment + '\\Scripts\\pip.exe', 'install', 'Pillow'], shell=True)
    else:
        print("  **Nothing more to install**")
895035
def do_py(self, args: argparse.Namespace) -> bool:
        """"""
        from .pyscript_bridge import PyscriptBridge
        if self._in_py:
            err = "Recursively entering interactive Python consoles is not allowed."
            self.perror(err, traceback_war=False)
            return False

        try:
            self._in_py = True

            # Support the run command even if called prior to invoking an interactive interpreter
            def py_run(filename: str):
                """Run a Python script file in the interactive console.
                :param filename: filename of *.py script file to run
                """
                expanded_filename = os.path.expanduser(filename)

                # cmd_echo defaults to False for scripts. The user can always toggle this value in their script.
                bridge.cmd_echo = False

                try:
                    with open(expanded_filename) as f:
                        interp.runcode(f.read())
                except OSError as ex:
                    error_msg = "Error opening script file '{}': {}".format(expanded_filename, ex)
                    self.perror(error_msg, traceback_war=False)

            def py_quit():
                """Function callable from the interactive Python console to exit that environment"""
                raise EmbeddedConsoleExit

            # Set up Python environment
            bridge = PyscriptBridge(self)
            self.pystate[self.pyscript_name] = bridge
            self.pystate['run'] = py_run
            self.pystate['quit'] = py_quit
            self.pystate['exit'] = py_quit

            if self.locals_in_py:
                self.pystate['self'] = self
            elif 'self' in self.pystate:
                del self.pystate['self']

            localvars = self.pystate
            from code import InteractiveConsole
            interp = InteractiveConsole(locals=localvars)
            interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')

            # Check if the user is running a Python statement on the command line
            if args.command:
                full_command = args.command
                if args.remainder:
                    full_command += ' ' + ' '.join(args.remainder)

                # Set cmd_echo to True so PyscriptBridge statements like: py app('help')
                # run at the command line will print their output.
                bridge.cmd_echo = True

                # noinspection PyBroadException
                try:
                    interp.runcode(full_command)
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

            # If there are no args, then we will open an interactive Python console
            else:
                # Set up readline for Python console
                if rl_type != RlType.NONE:
                    # Save cmd2 history
                    saved_cmd2_history = []
                    for i in range(1, readline.get_current_history_length() + 1):
                        # noinspection PyArgumentList
                        saved_cmd2_history.append(readline.get_history_item(i))

                    readline.clear_history()

                    # Restore py's history
                    for item in self.py_history:
                        readline.add_history(item)

                    if self.use_rawinput and self.completekey:
                        # Set up tab completion for the Python console
                        # rlcompleter relies on the default settings of the Python readline module
                        if rl_type == RlType.GNU:
                            saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
                            rl_basic_quote_characters.value = orig_rl_basic_quotes

                            if 'gnureadline' in sys.modules:
                                # rlcompleter imports readline by name, so it won't use gnureadline
                                # Force rlcompleter to use gnureadline instead so it has our settings and history
                                saved_readline = None
                                if 'readline' in sys.modules:
                                    saved_readline = sys.modules['readline']

                                sys.modules['readline'] = sys.modules['gnureadline']

                        saved_delims = readline.get_completer_delims()
                        readline.set_completer_delims(orig_rl_delims)

                        # rlcompleter will not need cmd2's custom display function
                        # This will be restored by cmd2 the next time complete() is called
                        if rl_type == RlType.GNU:
                            readline.set_completion_display_matches_hook(None)
                        elif rl_type == RlType.PYREADLINE:
                            # noinspection PyUnresolvedReferences
                            readline.rl.mode._display_completions = self._display_matches_pyreadline

                        # Save off the current completer and set a new one in the Python console
                        # Make sure it tab completes from its locals() dictionary
                        saved_completer = readline.get_completer()
                        interp.runcode("from rlcompleter import Completer")
                        interp.runcode("import readline")
                        interp.runcode("readline.set_completer(Completer(locals()).complete)")

                # Set up sys module for the Python console
                self._reset_py_display()

                saved_sys_stdout = sys.stdout
                sys.stdout = self.stdout

                saved_sys_stdin = sys.stdin
                sys.stdin = self.stdin

                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
                instructions = ('End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`.\n'
                                'Non-Python commands can be issued with: {}("your command")\n'
                                'Run Python code from external script files with: run("script.py")'
                                .format(self.pyscript_name))

                # noinspection PyBroadException
                try:
                    interp.interact(banner="Python {} on {}\n{}\n\n{}\n".
                                    format(sys.version, sys.platform, cprt, instructions))
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

                finally:
                    sys.stdout = saved_sys_stdout
                    sys.stdin = saved_sys_stdin

                    # Set up readline for cmd2
                    if rl_type != RlType.NONE:
                        # Save py's history
                        self.py_history.clear()
                        for i in range(1, readline.get_current_history_length() + 1):
                            # noinspection PyArgumentList
                            self.py_history.append(readline.get_history_item(i))

                        readline.clear_history()

                        # Restore cmd2's history
                        for item in saved_cmd2_history:
                            readline.add_history(item)

                        if self.use_rawinput and self.completekey:
                            # Restore cmd2's tab completion settings
                            readline.set_completer(saved_completer)
                            readline.set_completer_delims(saved_delims)

                            if rl_type == RlType.GNU:
                                rl_basic_quote_characters.value = saved_basic_quotes

                                if 'gnureadline' in sys.modules:
                                    # Restore what the readline module pointed to
                                    if saved_readline is None:
                                        del(sys.modules['readline'])
                                    else:
                                        sys.modules['readline'] = saved_readline

        except KeyboardInterrupt:
            pass

        finally:
            self._in_py = False

        return self._should_quit