Run and profile a given Python script.

    :param str filepath: The filepath of the script to profile
350276
def profile(ctx, filepath, calltree=False):
    

    filepath = pathlib.Path(filepath)
    if not filepath.is_file():
        log("profile", f"no such script {filepath!s}", LogLevel.ERROR)
    else:
        if calltree:
            log("profile", f"profiling script {filepath!s} calltree")
            ctx.run(
                (
                    f"python -m cProfile -o .profile.cprof {filepath!s}"
                    " && pyprof2calltree -k -i .profile.cprof"
                    " && rm -rf .profile.cprof"
                )
            )
        else:
            log("profile", f"profiling script {filepath!s}")
            ctx.run(f"vprof -c cmhp {filepath!s}")
1169140
def search_script_file(self, path, file_name):
        
        with open(os.path.join(path, file_name), "r") as script:
            self.search_script(script.read())
1298832
def runprofile(mainfunction, output, timeout = 0, calibrate=False):
    '''
    
    '''
    if noprofiler == True:
            print('ERROR: profiler and/or pstats library missing ! Please install it (probably package named python-profile) before running a profiling !')
            return False
    # This is the main function for profiling
    def _profile():
        profile.run(mainfunction, output)
    print('=> RUNNING FUNCTIONS PROFILER\n\n'); sys.stdout.flush();
    # Calibrate the profiler (only use this if the profiler produces some funny stuff, but calibration can also produce even more funny stuff with the latest cProfile of Python v2.7! So you should only enable calibration if necessary)
    if calibrate:
        print('Calibrating the profiler...'); sys.stdout.flush();
        cval = calibrateprofile()
        print('Calibration found value : %s' % cval); sys.stdout.flush();
    print('Initializing the profiler...'); sys.stdout.flush();
    # Run in timeout mode (if the function cannot ends by itself, this is the best mode: the function must ends for the profile to be saved)
    if timeout > 0:
        pthread = KThread(target=_profile) # we open the function with the profiler, in a special killable thread (see below why)
        print('Will now run the profiling and terminate it in %s seconds. Results will be saved in %s' % (str(timeout), str(output))); sys.stdout.flush();
        print('\nCountdown:'); sys.stdout.flush();
        for i in range(0,5):
                print(str(5-i))
                sys.stdout.flush()
                time.sleep(1)
        print('0\nStarting to profile...'); sys.stdout.flush();
        pthread.start() # starting the thread
        time.sleep(float(timeout)) # after this amount of seconds, the thread gets killed and the profiler will end its job
        print('\n\nFinishing the profile and saving to the file %s' % str(output)); sys.stdout.flush();
        pthread.kill() # we must end the main function in order for the profiler to output its results (if we didn't launch a thread and just closed the process, it would have done no result)
    # Run in full length mode (we run the function until it ends)
    else:
        print("Running the profiler, please wait until the process terminates by itself (if you forcequit before, the profile won't be saved)")
        _profile()
    print('=> Functions Profile done !')
    return True
739894
def run(filepath, wsgiapp, host, port, reload, interval,
        static, static_root, static_dirs, lineprof, lineprof_file, validate):
    
    insert_import_path_to_sys_modules(filepath)
    module = SourceFileLoader('module', filepath).load_module()
    app = getattr(module, wsgiapp)

    if static:
        from wsgi_static_middleware import StaticMiddleware
        app = StaticMiddleware(app, static_root=static_root, static_dirs=static_dirs)

    if validate:
        from wsgiref.validate import validator
        app = validator(app)

    if lineprof:
        # Caution: wsgi-lineprof is still pre-alpha. Except breaking API Changes.
        from wsgi_lineprof.middleware import LineProfilerMiddleware
        from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter

        if lineprof_file:
            # Now wsgi-lineprof is now supported only 1 file checking.
            lineprof_file = lineprof_file[0]
        else:
            lineprof_file = os.path.basename(filepath)
        filters = [FilenameFilter(lineprof_file), TotalTimeSorter()]
        app = LineProfilerMiddleware(app, filters=filters)

    if reload:
        run_live_reloading_server(interval, app=app, host=host, port=port)
    else:
        run_server(app=app, host=host, port=port)
1078866
protected void executeScript(String scriptPath) {
        URL scriptUrl = null;
        try {
            if (scriptPath.startsWith("classpath:")) {
                String script = scriptPath.substring("classpath:".length());
                scriptUrl = ClassUtil.getResource(script);
                if (scriptUrl == null) {
                    log.warn("Script '{}' not found!", scriptPath);
                }
            } else {
                File file = new File(scriptPath);
                if (file.exists()) {
                    scriptUrl = file.toURI().toURL();
                } else {
                    log.warn("Script '{}' not found!", scriptPath);
                }
            }

            // execute the script
            if (scriptUrl != null) {
                executeScript(scriptUrl);
            }

        } catch (Exception e) {
            log.error("Failed to parse '{}' as a url", scriptPath);
        }
    }
590284
def maybe_profiled(profile_path):
  
  if not profile_path:
    yield
    return

  import cProfile
  profiler = cProfile.Profile()
  try:
    profiler.enable()
    yield
  finally:
    profiler.disable()
    profiler.dump_stats(profile_path)
    view_cmd = green('gprof2dot -f pstats {path} | dot -Tpng -o {path}.png && open {path}.png'
                     .format(path=profile_path))
    logging.getLogger().info(
      'Dumped profile data to: {}\nUse e.g. {} to render and view.'.format(profile_path, view_cmd)
    )
871866
def runprofilerandshow(funcname, profilepath, argv='', *args, **kwargs):
    '''
    
    '''
    functionprofiler.runprofile(funcname+'(\''+argv+'\')', profilepath, *args, **kwargs)
    print 'Showing profile (windows should open in the background)'; sys.stdout.flush();
    functionprofiler.browseprofilegui(profilepath)
60330
def _run_cmd(cmd, ctx, glob, loc):  # pragma: no cover
    """"""
    if PDB:
        _enable_pdb()
    if IPYTHON:
        from IPython import start_ipython
        args_ipy = ['-i', '--gui=qt']
        ns = glob.copy()
        ns.update(loc)
        return start_ipython(args_ipy, user_ns=ns)
    # Profiling. The builtin `profile` is added in __init__.
    prof = __builtins__.get('profile', None)
    if prof:
        prof = __builtins__['profile']
        return _profile(prof, cmd, glob, loc)
    return exec_(cmd, glob, loc)
291405
def load_from_file(filepath):
        
        class_inst = None
        expected_class = "Py3status"
        module_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
        if file_ext.lower() == ".py":
            py_mod = imp.load_source(module_name, filepath)
            if hasattr(py_mod, expected_class):
                class_inst = py_mod.Py3status()
        return class_inst
1111170
def run_script(self, filename=None, silent=False, set_focus=False,
                   args=None):
        """"""
        if filename is None:
            self.shell.interpreter.restore_stds()
            filename, _selfilter = getopenfilename(
                    self, _("Run Python script"), getcwd_or_home(),
                    _("Python scripts")+" (*.py ; *.pyw ; *.ipy)")
            self.shell.interpreter.redirect_stds()
            if filename:
                os.chdir( osp.dirname(filename) )
                filename = osp.basename(filename)
            else:
                return
        logger.debug("Running script with %s", args)
        filename = osp.abspath(filename)
        rbs = remove_backslashes
        command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args))
        if set_focus:
            self.shell.setFocus()
        if self.dockwidget and not self.ismaximized:
            self.dockwidget.setVisible(True)
            self.dockwidget.raise_()
        self.shell.write(command+'\n')
        self.shell.run_command(command)
612048
def install(self, filepath):
        '''  '''
        if not os.path.exists(filepath):
            raise EnvironmentError('file "%s" not exists.' % filepath)

        ideviceinstaller = must_look_exec('ideviceinstaller')
        os.system(subprocess.list2cmdline([ideviceinstaller, '-u', self.udid, '-i', filepath]))
858003
def run_hive_script(script):
    
    if not os.path.isfile(script):
        raise RuntimeError("Hive script: {0} does not exist.".format(script))
    return run_hive(['-f', script])
413217
def runpath(path, argv, filename=None, threads=True, verbose=False):
    
    _run(threads, verbose, 'runpath', filename, path, argv)
249045
def __run_py_file(self, filepath, module_name):
        

        # Import the module
        spec = importlib.util.spec_from_file_location(module_name, filepath)
        delta_py = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(delta_py)

        # Get the python file's directory path
        # Note: we add a separator for backward compatibility, as existing DeltaPy subclasses
        # may assume that delta_dir ends with a separator
        dir_ = dirname(filepath) + os.sep

        # Search for subclasses of DeltaPy
        for name in dir(delta_py):
            obj = getattr(delta_py, name)
            if inspect.isclass(obj) and not obj == DeltaPy and issubclass(
                    obj, DeltaPy):

                delta_py_inst = obj(
                    self.current_db_version(), dir_, self.dirs, self.pg_service,
                    self.upgrades_table, variables=self.variables)
                delta_py_inst.run()
1359743
def dump_profiles(self, path):
        
        if self.profiler_collector is not None:
            self.profiler_collector.dump_profiles(path)
        else:
            raise RuntimeError("'spark.python.profile' configuration must be set "
                               "to 'true' to enable Python profile.")
253365
def AddFile(self, filepath):
    
    if filepath not in self._files:
      self._files.add(filepath)
      return True
    return False
1163683
def load(filepath):
        '''
        
        '''

        try:
            with open(filepath, "r") as fh:
                source = fh.read()
        except Exception as e:
            return None, e
        return source, None