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
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
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"])
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"]
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']
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"])
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']
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])
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"])
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()
def load(self): # License note: # It is a reimplementation based on the original # buildbot.config.FileLoader and buildbot.config.loadConfigDict # implementation. config = self.path.absolute() basedir = config.parent if not config.exists(): raise ConfigErrors([ f"configuration file '{config}' does not exist" ]) try: with config.open('r'): pass except IOError as e: raise ConfigErrors([ f'unable to open configuration file {config}: {e}' ]) log.info(f'Loading configuration from {config}') # execute the config file local_dict = { # inject global variables, useful for including configurations **self.inject_globals, '__file__': config } old_sys_path = sys.path[:] sys.path.append(str(basedir)) try: try: execfile(config, local_dict) except ConfigErrors: raise except SyntaxError: exc = traceback.format_exc() error(f'encountered a SyntaxError while parsing config file:\n' f'{exc}', always_raise=True) except Exception: exc = traceback.format_exc() error(f'error while parsing config file: {exc} (traceback in ' f'logfile)', always_raise=True) finally: sys.path[:] = old_sys_path if self.variable not in local_dict: error(f'Configuration file {config} does not define variable' f'`{self.variable}`', always_raise=True) return local_dict[self.variable]
def loadConfigDict(basedir, configFileName): if not os.path.isdir(basedir): raise ConfigErrors([f"basedir '{basedir}' does not exist"]) filename = os.path.join(basedir, configFileName) if not os.path.exists(filename): raise ConfigErrors([f"configuration file '{filename}' does not exist"]) try: with open(filename, "r", encoding='utf-8'): pass except IOError as e: raise ConfigErrors([ f"unable to open configuration file {repr(filename)}: {e}" ]) from e log.msg(f"Loading configuration from {repr(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( f"encountered a SyntaxError while parsing config file:\n{traceback.format_exc()} ", always_raise=True) except Exception: log.err(failure.Failure(), 'error while parsing config file:') error( f"error while parsing config file: {sys.exc_info()[1]} (traceback in logfile)", always_raise=True) finally: sys.path[:] = old_sys_path if 'BuildmasterConfig' not in localDict: error( f"Configuration file {repr(filename)} does not define 'BuildmasterConfig'", always_raise=True, ) return filename, localDict['BuildmasterConfig']
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())
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__"]
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]
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
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
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()
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]
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()
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))
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
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))
func(1, 2) parameters = inspect.signature(func).parameters dummyParameters = parameters.copy() dummyParameters['c'] = FakeParameter("fake", "fake") fakeSig = FakeSignature(dummyParameters) self.assertRaises(TypeError, _passedSignature, fakeSig, (1, 2), {}) if not getattr(inspect, "signature", None): test_invalidParameterType.skip = "inspect.signature() not available" if sys.version_info >= (3,): _path = FilePath(__file__).parent().child("_deprecatetests.py.3only") _g = {} execfile(_path.path, _g) KeywordOnlyTests = _g["KeywordOnlyTests"] else: from twisted.trial.unittest import TestCase class KeywordOnlyTests(TestCase): """ A dummy class to show that this test file was discovered but the tests are unable to be ran in this version of Python. """ skip = ( "keyword only arguments (PEP 3102) are " "only in Python 3 and higher") def test_notAvailable(self):
""" A wrapper for L{twisted.internet.test._awaittests}, as that test module includes keywords not valid in Pythons before 3.5. """ from __future__ import absolute_import, division from twisted.python.compat import _PY35PLUS, _PY3, execfile from twisted.python.filepath import FilePath from twisted.trial import unittest if _PY35PLUS: _path = FilePath(__file__).parent().child("_awaittests.py.3only") _g = {"__name__": __name__ + ".3-only.awaittests"} execfile(_path.path, _g) AwaitTests = _g["AwaitTests"] else: class AwaitTests(unittest.SynchronousTestCase): """ A dummy class to show that this test file was discovered but the tests are unable to be run in this version of Python. """ skip = "async/await is not available before Python 3.5" def test_notAvailable(self): """ A skipped test to show that this was not run because the Python is too old. """