Example #1
0
def load_module_target_function(module_target_function):
    reloader.enable()
    check.inst_param(module_target_function, 'module_target_function',
                     ModuleTargetFunction)
    module = importlib.import_module(module_target_function.module_name)
    return DynamicObject(module, module_target_function.module_name,
                         module_target_function.fn_name)
Example #2
0
def load_file_target_function(file_target_function):
    reloader.enable()
    check.inst_param(file_target_function, 'file_target_function',
                     FileTargetFunction)
    module_name = os.path.splitext(
        os.path.basename(file_target_function.python_file))[0]
    module = imp.load_source(module_name, file_target_function.python_file)
    return DynamicObject(module, module_name, file_target_function.fn_name)
Example #3
0
    def test_blacklist(self):
        import reloader
        reloader.enable(['blacklisted'])

        self.write_module('blacklisted', "def func(): return True\n")
        self.write_module('testmodule', "import tests.blacklisted\n")

        import tests.blacklisted, tests.testmodule

        reloader.disable()
    def test_reload(self):
        import reloader
        reloader.enable()

        self.write_module('testmodule', "def func(): return 'Some code.'\n")
        from tests import testmodule
        self.assertEqual('Some code.', testmodule.func())

        self.write_module('testmodule', "def func(): return 'New code.'\n")
        reloader.reload(testmodule)
        self.assertEqual('New code.', testmodule.func())

        self.write_module('testmodule', "def func(): return 'More code.'\n")
        reloader.reload(testmodule)
        self.assertEqual('More code.', testmodule.func())
    def test_reload(self):
        import reloader

        reloader.enable()

        self.write_module("testmodule", "def func(): return 'Some code.'\n")
        import tests.testmodule

        self.assertEqual("Some code.", tests.testmodule.func())

        self.write_module("testmodule", "def func(): return 'New code.'\n")
        reloader.reload(tests.testmodule)
        self.assertEqual("New code.", tests.testmodule.func())

        self.write_module("testmodule", "def func(): return 'More code.'\n")
        reloader.reload(tests.testmodule)
        self.assertEqual("More code.", tests.testmodule.func())

        reloader.disable()
Example #6
0
 def import_apps():
     """import or reimport modules and exposed static files"""
     reloader.enable()
     folder = os.environ['WEB3PY_APPLICATIONS_FOLDER']
     app = bottle.default_app()
     app.routes.clear()
     # app.routes = app.routes[:]
     new_apps = []
     for app_name in os.listdir(folder):
         path = os.path.join(folder, app_name)
         if os.path.isdir(path) and not path.endswith('__'):
             try:
                 module = Reloader.MODULES.get(app_name)
                 if not module:
                     module = importlib.import_module(app_name)
                     Reloader.MODULES[app_name] = module
                     new_apps.append(path)
                 else:
                     reloader.reload(module)
                 Reloader.ERRORS[app_name] = None
             except:
                 print(traceback.format_exc())
                 Reloader.ERRORS[app_name] = traceback.format_exc()
     reloader.disable()
     # expose static files
     for path in new_apps:
         @bottle.route('/%s/static/<filename:path>' % path.split(os.path.sep)[-1])
         def server_static(filename, path=path):
             return bottle.static_file(filename, root=os.path.join(path, 'static'))
     # register routes
     routes = []
     def to_filename(module):
         filename = module.replace('.', os.path.sep)
         filename = os.path.join(filename, '__init__.py') if not module.count('.') else filename + '.py'
         return filename
     for route in app.routes:
         func = route.callback
         routes.append({'rule': route.rule,
                        'method': route.method,
                        'filename': to_filename(func.__module__),
                        'action': func.__name__})
     Reloader.ROUTES = sorted(routes, key=lambda item: item['rule'])
Example #7
0
def reloadallmodules():
    from config import es_constants
    from database import connectdb
    from database import querydb
    from apps.productmanagement import datasets
    from apps.productmanagement import products

    import reloader
    reloader.enable()
    # print reloader.get_dependencies(es_constants)
    reloader.reload(es_constants)
    reloader.reload(connectdb)
    reloader.reload(querydb)
    reloader.reload(datasets)
    reloader.reload(products)
    reloader.disable()
    # reloader.reload(sys.modules['config'])

    # from config import es_constants as constantsreloaded
    # for setting in constantsreloaded.es2globals:
    #     logger.info(setting + ': ' + str(es_constants.es2globals[setting]))
Example #8
0
import reloader
reloader.enable(blacklist = ['zope.interface', 'numpy','twisted','labrad'])
#import scripts.PulseSequences.subsequences.OpticalPumpingContinuous
#m = scripts.PulseSequences.subsequences.OpticalPumpingContinuous
import scripts.PulseSequences.delete_later
m = scripts.PulseSequences.delete_later

reloader.reload(m)

#print reloader.get_dependencies(scripts.PulseSequences.subsequences.OpticalPumpingContinuous)
Example #9
0
import reloader
reloader.enable(blacklist=['inspect','os','pickle','time','re','random','urllib','stripclub','math','udquery','sys','traceback','json','hashlib','irc','irc.bot','irc.client','ircbot','bot','chatterbotapi','socket'])

from irc import strings
from inspect import getmembers, isfunction
from bs4 import BeautifulSoup
import os,pickle,time,re,random,urllib2,urllib,requests,math,udquery,sys,traceback,json,hashlib,socket,datetime
import trpbot_commands
import stripclub
import redis
from irc.client import ip_numstr_to_quad,ip_quad_to_numstr
from Pastebin import PastebinAPI
from irc import bot as ircbot
from fnmatch import fnmatch
from chatterbotapi import ChatterBotFactory, ChatterBotType
cbfactory = ChatterBotFactory()
cbot = cbfactory.create(ChatterBotType.CLEVERBOT)

HOST = 'blacklotus.ca.us.quakenet.org' #'servercentral.il.us.quakenet.org'
PORT = 6667
NICK = 'TRPBot'
CHAN = '#trpbot'
AUTOJOIN = ['#theredpill',]
BOSS = 'tizenwork'
VERSION = '#theredpill bot v1.12'
AUTH = ''
CONFIG = 'config.json'

class TRPBot(ircbot.SingleServerIRCBot):
	def __init__(self,nickname=NICK,server=HOST,port=PORT,channel=CHAN):
		ircbot.SingleServerIRCBot.__init__(self,[(server, port)],nickname,nickname)
import reloader
reloader.enable(blacklist=[
    'numpy',
    'types',
    '_frozen_importlib',
    '_frozen_importlib_external',
    'importlib',
    '_imp',
    'heapq',
    'keyword',
    'imp',
    'typing',
    'oinspect',
    'traitlets',
    'matplotlib.pyplot',
    'matplotlib.image',
    'pickle',
    'cv2',
    'sklearn',
    'skimage.color.colorconv',
    'skimage.color.colorlabel',
    'skimage.color.delta_e',
    'skimage.feature',
    'tqdm',
    'scipy.ndimage.measurements',
])

import numpy as np
from overlay import writeOverlayText
import pygame
import time
Example #11
0
 def rescan_runner(number, frame):
     reloader.enable()
     reloader.reload(objshrunner)
     factories[0].runner.scan()
Example #12
0
 def scan(self,runner_folder):
     base_dir = os.path.abspath(os.path.dirname(__file__))
     loaded_module_names = sys.modules.keys()
     module_to_reload = []
     # pat to recognize a runner script
     has_runner_pat = re.compile('^@(after_|before_)?runner')
     
     for root,folders,files in os.walk(runner_folder):
         runner_folder_root = os.path.normpath(os.path.join(runner_folder,root))
         relpath = os.path.relpath(runner_folder_root,base_dir)
         paths = runner_folder_root.split('/')
         if (not relpath.startswith('..')) and len(relpath.split('/'))<2:
             sub_foldername = None
             if relpath=='.':
                 foldername = None
                 lib_folder = base_dir
             else:
                 foldername = paths[-1]
                 lib_folder = os.path.join(base_dir,paths[-1])
         else:
             foldername = paths[-2]
             sub_foldername = paths[-1]
             lib_folder = '/'+os.path.join(*paths[:-2])
         lib_folder_inserted = False
         if not lib_folder in sys.path:
             lib_folder_inserted = True
             sys.path.insert(0,lib_folder)
         for file in files:
             if file.startswith('.') or file.startswith('_'): continue
             elif file[-3:]=='.py':
                 # avoid to load twice if execution is from the runner subfolder for unit testing
                 file_path = os.path.join(runner_folder_root,file)
                 # only load file which wants to register runner
                 is_runner_script = False
                 fd = open(file_path,'r')
                 for line in fd:
                     if not has_runner_pat.search(line): continue
                     is_runner_script = True
                     break
                 fd.close()
                 if not is_runner_script: continue
                 
                 name = os.path.splitext(file)[0]
                 if sub_foldername is None:
                     module_name = '%s.%s' % (foldername,name)
                 else:
                     module_name = '%s.%s.%s' % (foldername,sub_foldername, name)
                 if module_name in loaded_module_names:
                     log.msg('reload runner %s' % (module_name))
                     module_to_reload.append(module_name)
                 else:
                     log.msg('load runner %s' % (module_name))
                     log.msg('lib ',lib_folder)
                     __import__(module_name, globals(), locals(), [], 0)
         # remove added path
         if lib_folder_inserted:
             sys.path.remove(lib_folder)
     if len(module_to_reload):
         reloader.enable()
         for module_name in module_to_reload:        
             reloader.reload(sys.modules[module_name])
         reloader.disable()
Example #13
0
from flask import Flask
import app as vnpy_app
from time import sleep
from flask import request
import json
import reloader
reloader.enable()
import handler
import script_handler
import pandas as pd
import matplotlib.pyplot as plt
app = Flask(__name__)


@app.route('/')
def root():
    plt.plot([3, 1, 4, 1, 5], 'ks-', mec='w', mew=5, ms=20)
    df = pd.DataFrame({'birth':[2000,2000,2000,2001,2001,2001,2002,2002,2002],\
    'name':['a','a','a','b','b','b','c' ,'c','c'],'code':[1,1,1,2,2,2,3,3,3],\
    'habit':['drink','smoke','drink','eat','smoke','drink','eat','smoke','drink',],\
    'value':['little','a few','some','some','little','a few','little','a few','some']})
    df_h = df.to_html()
    print(df_h)
    h = handler.fig_html()
    return h


@app.route('/oplist')
def oplist():
    l = []
    for item in handler.op_list:
Example #14
0
import sys
sys.path.append("..")

import reloader
reloader.enable()

from monitor import Reloader
import another
import time

r = Reloader()

while True:
    another.doit()
    r.poll()
    time.sleep(1)
Example #15
0
    def import_apps():
        """import or reimport modules and exposed static files"""
        reloader.enable()
        folder = os.environ['WEB3PY_APPS_FOLDER']
        app = bottle.default_app()
        app.routes.clear()
        new_apps = []
        for app_name in os.listdir(folder):
            path = os.path.join(folder, app_name)
            init = os.path.join(path, '__init__.py')
            if os.path.isdir(
                    path) and not path.endswith('__') and os.path.exists(init):
                module_name = 'apps.%s' % app_name
                try:
                    module = Reloader.MODULES.get(app_name)
                    if not module:
                        print('[  ] loading %s ...' % app_name)
                        module = importlib.machinery.SourceFileLoader(
                            module_name, init).load_module()
                        Reloader.MODULES[app_name] = module
                        new_apps.append(path)
                        print('\x1b[A[OK] loaded %s     ' % app_name)
                    else:
                        print('[  ] reloading %s ...' % app_name)
                        reloader.reload(module)
                        print('\x1b[A[OK] loaded %s     ' % app_name)
                    Reloader.ERRORS[app_name] = None
                except:
                    print('\x1b[A[FAILED] loading %s     ' % app_name)
                    print('\n'.join(
                        '    ' + line
                        for line in traceback.format_exc().split('\n')))
                    Reloader.ERRORS[app_name] = traceback.format_exc()
        reloader.disable()
        # expose static files
        for path in new_apps:

            @bottle.route('/%s/static/<filename:path>' %
                          path.split(os.path.sep)[-1])
            def server_static(filename, path=path):
                return bottle.static_file(filename,
                                          root=os.path.join(path, 'static'))

        # register routes
        routes = []

        def to_filename(module):
            filename = os.path.join(*module.split('.')[1:])
            filename = os.path.join(filename,
                                    '__init__.py') if not filename.count(
                                        os.sep) else filename + '.py'
            return filename

        for route in app.routes:
            func = route.callback
            routes.append({
                'rule': route.rule,
                'method': route.method,
                'filename': to_filename(func.__module__),
                'action': func.__name__
            })
        Reloader.ROUTES = sorted(routes, key=lambda item: item['rule'])