本文整理汇总了Python中globals函数的典型用法代码示例。如果您正苦于以下问题:Python globals函数的具体用法?Python globals怎么用?Python globals使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了globals函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: head
def head(self, **KWS):
## CHEETAH: generated from #def head at line 5, col 1.
trans = KWS.get("trans")
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
write(u'''<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=pt-br"></script>
<script type="text/javascript">
function initialize() {
var hotel = new google.maps.LatLng(''')
_v = VFSL([locals()]+SL+[globals(), builtin],"site.latitude",True) # u'$site.latitude' on line 9, col 40
if _v is not None: write(_filter(_v, rawExpr=u'$site.latitude')) # from line 9, col 40.
write(u''', ''')
_v = VFSL([locals()]+SL+[globals(), builtin],"site.longitude",True) # u'$site.longitude' on line 9, col 56
if _v is not None: write(_filter(_v, rawExpr=u'$site.longitude')) # from line 9, col 56.
write(u''');
var myOptions = {
zoom: 16,
center: hotel,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var hotelMarker = new google.maps.Marker({
position: hotel,
map: map,
title:"''')
_v = VFSL([locals()]+SL+[globals(), builtin],"site.name",True) # u'$site.name' on line 19, col 14
if _v is not None: write(_filter(_v, rawExpr=u'$site.name')) # from line 19, col 14.
write(u'''"
\t});
\t
\tvar content = "S\xedtio Tur\xedstico: ''')
_v = VFSL([locals()]+SL+[globals(), builtin],"site.name",True) # u'$site.name' on line 22, col 34
if _v is not None: write(_filter(_v, rawExpr=u'$site.name')) # from line 22, col 34.
write(u'''<br>"
\tvar infoWindow = new google.maps.InfoWindow({content: content});
\tinfoWindow.setPosition(hotel);
infoWindow.open(map);
}
</script>
''')
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
示例2: get_census_profile
def get_census_profile(geo_code, geo_level):
session = get_session()
try:
geo_summary_levels = get_summary_geo_info(geo_code, geo_level, session)
data = {}
for section in PROFILE_SECTIONS:
function_name = 'get_%s_profile' % section
if function_name in globals():
func = globals()[function_name]
data[section] = func(geo_code, geo_level, session)
# get profiles for province and/or country
for level, code in geo_summary_levels:
# merge summary profile into current geo profile
merge_dicts(data[section], func(code, level, session), level)
# tweaks to make the data nicer
# show 3 largest groups on their own and group the rest as 'Other'
group_remainder(data['service_delivery']['water_source_distribution'])
group_remainder(data['service_delivery']['refuse_disposal_distribution'])
group_remainder(data['service_delivery']['toilet_facilities_distribution'], 5)
group_remainder(data['demographics']['language_distribution'], 7)
return data
finally:
session.close()
示例3: get
def get(self, year, wwuidOrUsername):
wwuid = None
username = None
if len(wwuidOrUsername.split(".")) == 1:
wwuid = wwuidOrUsername
else:
username = wwuidOrUsername
# check if we're looking at current photos or not
if year == self.application.options.current_year:
if wwuid:
profile = query_by_wwuid(Profile, wwuid)
else:
profile = s.query(Profile).filter_by(username=str(username)).all()
else:
if wwuid:
profile = archive_s.query(globals()['Archive'+str(year)]).filter_by(wwuid=str(wwuid)).all()
else:
profile = archive_s.query(globals()['Archive'+str(year)]).filter_by(username=str(username)).all()
if len(profile) == 0:
self.write({'error': 'no profile found'})
elif len(profile) > 1:
self.write({'error': 'too many profiles found'})
else:
# now we've got just one profile, return the photo field attached to a known photo URI
profile = profile[0]
self.redirect("https://aswwu.com/media/img-sm/"+str(profile.photo))
示例4: __init__
def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem', heuristic='nullHeuristic'):
# Warning: some advanced Python magic is employed below to find the right functions and problems
# Get the search function from the name and heuristic
if fn not in dir(search):
raise AttributeError, fn + ' is not a search function in search.py.'
func = getattr(search, fn)
if 'heuristic' not in func.func_code.co_varnames:
print('[SearchAgent] using function ' + fn)
self.searchFunction = func
else:
if heuristic in globals().keys():
heur = globals()[heuristic]
elif heuristic in dir(search):
heur = getattr(search, heuristic)
else:
raise AttributeError, heuristic + ' is not a function in searchAgents.py or search.py.'
print('[SearchAgent] using function %s and heuristic %s' % (fn, heuristic))
# Note: this bit of Python trickery combines the search algorithm and the heuristic
self.searchFunction = lambda x: func(x, heuristic=heur)
# Get the search problem type from the name
if prob not in globals().keys() or not prob.endswith('Problem'):
raise AttributeError, prob + ' is not a search problem type in SearchAgents.py.'
self.searchType = globals()[prob]
print('[SearchAgent] using problem type ' + prob)
示例5: handler_spisok_iq
def handler_spisok_iq(type, source, parameters):
if not parameters:
reply(type,source,u'я могу список листов конфы глянуть,только выбери ключ!')
return
body=parameters.lower()
nick = source[2]
groupchat=source[1]
afl=''
if body.count(u'овнеры')>0:
afl='owner'
elif body.count(u'админы')>0:
afl='admin'
elif body.count(u'мемберы')>0:
afl='member'
elif body.count(u'изгои')>0:
afl='outcast'
if afl=='':
return
iq = xmpp.Iq('get')
id='item'+str(random.randrange(1000, 9999))
globals()['af_sh'].append(id)
iq.setTo(groupchat)
iq.setID(id)
query = xmpp.Node('query')
query.setNamespace('http://jabber.org/protocol/muc#admin')
ban=query.addChild('item', {'affiliation':afl})
iq.addChild(node=query)
JCON.SendAndCallForResponse(iq, handler_sp_answ, {'type': type, 'source': source})
示例6: readMesh
def readMesh(fn):
"""Read a nodes/elems model from file.
Returns an (x,e) tuple or None
"""
d = {}
pf.GUI.setBusy(True)
fil = file(fn,'r')
for line in fil:
if line[0] == '#':
line = line[1:]
globals().update(getParams(line))
dfil = file(filename,'r')
if mode == 'nodes':
d['coords'] = readNodes(dfil)
elif mode == 'elems':
elems = d.setdefault('elems',[])
e = readElems(dfil,int(nplex)) - int(offset)
elems.append(e)
elif mode == 'esets':
d['esets'] = readEsets(dfil)
else:
print("Skipping unrecognized line: %s" % line)
dfil.close()
pf.GUI.setBusy(False)
fil.close()
return d
示例7: parsemodel
def parsemodel(name):
parsestring = """
class %(name)s(basemodel):
_repr_expr='%(name)s'
def __init__(self):
self.pardata1 = open(XSPEC_MODULE_PATH+'/%(name)s.dat1', 'r').readlines()
self.pardata2 = open(XSPEC_MODULE_PATH+'/%(name)s.dat2', 'r').readlines()
basemodel.__init__(self)
for lines in self.pardata1:
self.parameters.append(parameter(lines.split()))
for par in self.parameters:
par.model=repr(self)
par.group=0
for lines in self.pardata2:
linestr=lines.split()
(numbkey, index, comp, modelname, parname, unit) = linestr[:6]
self.__dict__[parname] = self.parameters[int(index)-1]
self.__dict__[parname].name=parname
self.__parameter_names__.append(parname)
try:float(unit)
except:self.__dict__[parname].unit=unit
self.parlength=len(self.parameters)
#def update(self):
#for pars in [x for x in self.parameters if x.group == 0]:
#object.__setattr__(self, pars.name, pars)
""" % {'name':name}
exec(parsestring)
clsobj = locals()[name]
globals().update({name:clsobj})
示例8: help
def help(player, string):
"""Display help a console command."""
if string:
try:
func = globals()[string]
if callable(func) and func.__doc__:
for s in func.__doc__.split('\n'):
FantasyDemo.addChatMsg(-1, s)
else:
raise 'Not callable'
except:
FantasyDemo.addChatMsg(-1, 'No help for ' + string)
else:
isCallable = lambda x: callable(globals()[x])
ignoreList = ('getV4FromString', 'help')
notIgnored = lambda x: x not in ignoreList
keys = filter(isCallable, globals().keys())
keys = filter(notIgnored, keys)
keys.sort()
FantasyDemo.addChatMsg(-1, '/help {command} for more info.')
stripper = lambda c: c not in '[]\'"'
string = filter(stripper, str(keys))
FantasyDemo.addChatMsg(-1, string)
示例9: executor
def executor(queue,task):
""" the background process """
logging.debug(' task started')
stdout, sys.stdout = sys.stdout, cStringIO.StringIO()
try:
if task.app:
os.chdir(os.environ['WEB2PY_PATH'])
from gluon.shell import env
from gluon.dal import BaseAdapter
from gluon import current
level = logging.getLogger().getEffectiveLevel()
logging.getLogger().setLevel(logging.WARN)
_env = env(task.app,import_models=True)
logging.getLogger().setLevel(level)
scheduler = current._scheduler
scheduler_tasks = current._scheduler.tasks
_function = scheduler_tasks[task.function]
globals().update(_env)
args = loads(task.args)
vars = loads(task.vars, object_hook=_decode_dict)
result = dumps(_function(*args,**vars))
else:
### for testing purpose only
result = eval(task.function)(
*loads(task.args, object_hook=_decode_dict),
**loads(task.vars, object_hook=_decode_dict))
stdout, sys.stdout = sys.stdout, stdout
queue.put(TaskReport(COMPLETED, result,stdout.getvalue()))
except BaseException,e:
sys.stdout = stdout
tb = traceback.format_exc()
queue.put(TaskReport(FAILED,tb=tb))
示例10: _create
def _create(self, name, params):
self._check_session(params)
is_sr_create = name == 'SR.create'
is_vlan_create = name == 'VLAN.create'
# Storage Repositories have a different API
expected = is_sr_create and 10 or is_vlan_create and 4 or 2
self._check_arg_count(params, expected)
(cls, _) = name.split('.')
ref = is_sr_create and \
_create_sr(cls, params) or \
is_vlan_create and \
_create_vlan(params[1], params[2], params[3]) or \
_create_object(cls, params[1])
# Call hook to provide any fixups needed (ex. creating backrefs)
after_hook = 'after_%s_create' % cls
if after_hook in globals():
globals()[after_hook](ref, params[1])
obj = get_record(cls, ref)
# Add RO fields
if cls == 'VM':
obj['power_state'] = 'Halted'
return ref
示例11: exec_func
def exec_func(name,*args,**kwargs):
if globals().has_key(name):
func = globals()[name]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return func(options,*args,**kwargs)
raise ValueError, name
示例12: timecheck
def timecheck():
timenow = time.strftime('%M%S')
# Fuer puenktlichere Umschaltung die Sleep-Zeit verkuerzen in der letzten Sekunde vor der vollen Stunde
# For a better timing of the switch, have shorter sleep-time in last second before new hour
global sleeptime
if timenow == '5959':
sleeptime = 0.001
else:
sleeptime = 0.01
# Timer fuer die Umschaltung zur vollen Stunde
# Timer to switch at every new hour
if timenow == '0000':
global now, then
# gmtime, damit Zeitumstellung keine Rolle spielt
# gmtime, so that daylight-saving-time won't do any harm
now = time.strftime('%H%M%S', time.gmtime())
if 'then' not in globals():
then = '999999'
if now != then:
logging.debug("Time-Check: the time to switch is now")
umschalt()
then = now
# Timer fuer den Software-Watchdog (muss jede Sekunde aufgerufen werden)
# Timer to notify Software-Watchdog (which has to be called every second)
global nowsecs, thensecs
nowsecs = time.strftime('%S')
if 'thensecs' not in globals():
thensecs = '99'
if nowsecs != thensecs:
watchdogcall()
thensecs = nowsecs
示例13: test_reusable_scope
def test_reusable_scope(self):
scope = let(a="tacos", b="soup", c="cake")
d = "godzilla"
with scope:
self.assertEquals(a, "tacos")
self.assertEquals(b, "soup")
self.assertEquals(c, "cake")
self.assertEquals(d, "godzilla")
a = "fajita"
b = "stew"
d = "mothra"
self.assertFalse("a" in locals())
self.assertFalse("b" in locals())
self.assertFalse("c" in locals())
self.assertTrue("d" in locals())
self.assertFalse("a" in globals())
self.assertFalse("b" in globals())
self.assertFalse("c" in globals())
self.assertFalse("d" in globals())
self.assertEquals(d, "mothra")
with scope:
self.assertEquals(a, "fajita")
self.assertEquals(b, "stew")
self.assertEquals(c, "cake")
self.assertEquals(d, "mothra")
示例14: test_nonlocal_del
def test_nonlocal_del(self):
# weird pythonism: the statement `del a` WITHOUT a `global a`
# causes the compiler to create an empty fast local variable
# named `a` with a NULL value, which it then deletes (setting
# the value again to NULL. In other words, the del statement
# counts as an assignment in the eyes of the compiler.
global a, b
a = "remove me"
with let(a="tacos", b="soda") as my_scope:
self.assertTrue("a" in globals())
self.assertTrue("b" in globals())
del a
del b
self.assertTrue("a" not in my_scope)
self.assertTrue("b" not in my_scope)
self.assertEquals(a, "remove me")
del a
self.assertTrue("a" not in globals())
self.assertTrue("b" not in globals())
示例15: onReload
def onReload(self, moduleName="SegmentCAD"):
#Generic reload method for any scripted module.
#ModuleWizard will subsitute correct default moduleName.
import imp, sys, os, slicer
widgetName = moduleName + "Widget"
# reload the source code
# - set source file path
# - load the module to the global space
filePath = eval('slicer.modules.%s.path' % moduleName.lower())
p = os.path.dirname(filePath)
if not sys.path.__contains__(p):
sys.path.insert(0,p)
fp = open(filePath, "r")
globals()[moduleName] = imp.load_module(
moduleName, fp, filePath, ('.py', 'r', imp.PY_SOURCE))
fp.close()
# rebuild the widget
# - find and hide the existing widget
# - create a new widget in the existing parent
# parent = slicer.util.findChildren(name='%s Reload' % moduleName)[0].parent()
parent = self.parent
for child in parent.children():
try:
child.hide()
except AttributeError:
pass
globals()[widgetName.lower()] = eval(
'globals()["%s"].%s(parent)' % (moduleName, widgetName))
globals()[widgetName.lower()].setup()