本文整理汇总了Python中twisted.python.compat.execfile函数的典型用法代码示例。如果您正苦于以下问题:Python execfile函数的具体用法?Python execfile怎么用?Python execfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了execfile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
def render(self, request):
"""
Render me to a web client.
Load my file, execute it in a special namespace (with 'request' and
'__file__' global vars) and finish the request. Output to the web-page
will NOT be handled with print - standard output goes to the log - but
with request.write.
"""
request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
namespace = {'request': request,
'__file__': _coerceToFilesystemEncoding("", self.filename),
'registry': self.registry}
try:
execfile(self.filename, namespace, namespace)
except IOError as e:
if e.errno == 2: #file not found
request.setResponseCode(http.NOT_FOUND)
request.write(resource.NoResource("File not found.").render(request))
except:
io = NativeStringIO()
traceback.print_exc(file=io)
output = util._PRE(io.getvalue())
if _PY3:
output = output.encode("utf8")
request.write(output)
request.finish()
return server.NOT_DONE_YET
示例2: test_execfileGlobals
def test_execfileGlobals(self):
"""
L{execfile} executes the specified file in the given global namespace.
"""
script = self.writeScript(u"foo += 1\n")
globalNamespace = {"foo": 1}
execfile(script.path, globalNamespace)
self.assertEqual(2, globalNamespace["foo"])
示例3: getVersion
def getVersion(self):
"""
@return: A L{Version} specifying the version number of the project
based on live python modules.
"""
namespace = {}
execfile(self.directory.child("_version.py").path, namespace)
return namespace["version"]
示例4: test_execfileUniversalNewlines
def test_execfileUniversalNewlines(self):
"""
L{execfile} reads in the specified file using universal newlines so
that scripts written on one platform will work on another.
"""
for lineEnding in u"\n", u"\r", u"\r\n":
script = self.writeScript(u"foo = 'okay'" + lineEnding)
globalNamespace = {"foo": None}
execfile(script.path, globalNamespace)
self.assertEqual("okay", globalNamespace["foo"])
示例5: loadConfigDict
def loadConfigDict(basedir, configFileName):
if not os.path.isdir(basedir):
raise ConfigErrors([
"basedir '%s' does not exist" % (basedir,),
])
filename = os.path.join(basedir, configFileName)
if not os.path.exists(filename):
raise ConfigErrors([
"configuration file '%s' does not exist" % (filename,),
])
try:
with open(filename, "r"):
pass
except IOError as e:
raise ConfigErrors([
"unable to open configuration file %r: %s" % (filename, e),
])
log.msg("Loading configuration from %r" % (filename,))
# execute the config file
localDict = {
'basedir': os.path.expanduser(basedir),
'__file__': os.path.abspath(filename),
}
old_sys_path = sys.path[:]
sys.path.append(basedir)
try:
try:
execfile(filename, localDict)
except ConfigErrors:
raise
except SyntaxError:
error("encountered a SyntaxError while parsing config file:\n%s " %
(traceback.format_exc(),),
always_raise=True,
)
except Exception:
log.err(failure.Failure(), 'error while parsing config file:')
error("error while parsing config file: %s (traceback in logfile)" %
(sys.exc_info()[1],),
always_raise=True,
)
finally:
sys.path[:] = old_sys_path
if 'BuildmasterConfig' not in localDict:
error("Configuration file %r does not define 'BuildmasterConfig'"
% (filename,),
always_raise=True,
)
return filename, localDict['BuildmasterConfig']
示例6: loadFile
def loadFile(self, filename):
g, l = self.setupConfigNamespace(), {}
execfile(filename, g, l)
if 'zone' not in l:
raise ValueError("No zone defined in " + filename)
self.records = {}
for rr in l['zone']:
if isinstance(rr[1], dns.Record_SOA):
self.soa = rr
self.records.setdefault(rr[0].lower(), []).append(rr[1])
示例7: test_execfileGlobalsAndLocals
def test_execfileGlobalsAndLocals(self):
"""
L{execfile} executes the specified file in the given global and local
namespaces.
"""
script = self.writeScript(u"foo += 1\n")
globalNamespace = {"foo": 10}
localNamespace = {"foo": 20}
execfile(script.path, globalNamespace, localNamespace)
self.assertEqual(10, globalNamespace["foo"])
self.assertEqual(21, localNamespace["foo"])
示例8: getVersion
def getVersion(base):
"""
Extract the version number.
@rtype: str
@returns: The version number of the project, as a string like
"2.0.0".
"""
vfile = os.path.join(base, '_version.py')
ns = {'__name__': 'Nothing to see here'}
execfile(vfile, ns)
return ns['version'].base()
示例9: getVersion
def getVersion(self):
"""
@return: A L{incremental.Version} specifying the version number of the
project based on live python modules.
"""
namespace = {}
directory = self.directory
while not namespace:
if directory.path == "/":
raise Exception("Not inside a Twisted project.")
elif not directory.basename() == "twisted":
directory = directory.parent()
else:
execfile(directory.child("_version.py").path, namespace)
return namespace["__version__"]
示例10: __init__
def __init__(self, filename):
self.chapters = []
self.indexFilename = None
global Chapter
Chapter = self.Chapter
global getNumber
getNumber = self.getNumber
global getReference
getReference = self.getNumber
global Index
Index = self.Index
if filename:
execfile(filename, globals())
示例11: ResourceScript
def ResourceScript(path, registry):
"""
I am a normal py file which must define a 'resource' global, which should
be an instance of (a subclass of) web.resource.Resource; it will be
renderred.
"""
cs = CacheScanner(path, registry)
glob = {'__file__': path,
'resource': noRsrc,
'registry': registry,
'cache': cs.cache,
'recache': cs.recache}
try:
execfile(path, glob, glob)
except AlreadyCached, ac:
return ac.args[0]
示例12: getExtensions
def getExtensions():
"""
Get all extensions from core and all subprojects.
"""
extensions = []
if not sys.platform.startswith("java"):
for dir in os.listdir("twisted") + [""]:
topfiles = os.path.join("twisted", dir, "topfiles")
if os.path.isdir(topfiles):
ns = {}
setup_py = os.path.join(topfiles, "setup.py")
execfile(setup_py, ns, ns)
if "extensions" in ns:
extensions.extend(ns["extensions"])
return extensions
示例13: getVersion
def getVersion(proj, base="twisted"):
"""
Extract the version number for a given project.
@param proj: the name of the project. Examples are "core",
"conch", "words", "mail".
@rtype: str
@returns: The version number of the project, as a string like
"2.0.0".
"""
if proj == "core":
vfile = os.path.join(base, "_version.py")
else:
vfile = os.path.join(base, proj, "_version.py")
ns = {"__name__": "Nothing to see here"}
execfile(vfile, ns)
return ns["version"].base()
示例14: render
def render(self, request):
"""Render me to a web client.
Load my file, execute it in a special namespace (with 'request' and
'__file__' global vars) and finish the request. Output to the web-page
will NOT be handled with print - standard output goes to the log - but
with request.write.
"""
request.setHeader("x-powered-by","Twisted/%s" % copyright.version)
namespace = {'request': request,
'__file__': self.filename,
'registry': self.registry}
try:
execfile(self.filename, namespace, namespace)
except IOError, e:
if e.errno == 2: #file not found
request.setResponseCode(http.NOT_FOUND)
request.write(resource.NoResource("File not found.").render(request))
示例15: ResourceScript
def ResourceScript(path, registry):
"""
I am a normal py file which must define a 'resource' global, which should
be an instance of (a subclass of) web.resource.Resource; it will be
renderred.
"""
cs = CacheScanner(path, registry)
glob = {'__file__': _coerceToFilesystemEncoding("", path),
'resource': noRsrc,
'registry': registry,
'cache': cs.cache,
'recache': cs.recache}
try:
execfile(path, glob, glob)
except AlreadyCached as ac:
return ac.args[0]
rsrc = glob['resource']
if cs.doCache and rsrc is not noRsrc:
registry.cachePath(path, rsrc)
return rsrc