def generatesurname(species):
# check species
if species == 1:
sl=sum(1 for line in open('assets/Generators/NameGenerator/HumanSurnames.txt'))
sr = random.randrange(sl)+1
sn = linecache.getline('assets/Generators/NameGenerator/HumanSurnames.txt', sr)
# Delete Newline at end
elif species == 2:
sl=sum(1 for line in open('assets/Generators/NameGenerator/RobotSurnames.txt'))
sr = random.randrange(sl)+1
sn = linecache.getline('assets/Generators/NameGenerator/RobotSurnames.txt', sr)
# Delete Newline at end
else:
# error msg
print('please specify species for name generator')
return
linecache.clearcache()
sm = len(sn)-1
lastname = sn[:sm]
return lastname
# newname = Name('human',2)
# newsurname = Surname('human')
# print(newname,newsurname)
python类clearcache()的实例源码
def clear_trace_filter_cache():
'''
Clear the trace filter cache.
Call this after reloading.
'''
global should_trace_hook
try:
# Need to temporarily disable a hook because otherwise
# _filename_to_ignored_lines.clear() will never complete.
old_hook = should_trace_hook
should_trace_hook = None
# Clear the linecache
linecache.clearcache()
_filename_to_ignored_lines.clear()
finally:
should_trace_hook = old_hook
def getRow(self,recordnum,path,size):
filenum = (recordnum-1)/size
linenum = (recordnum-1)%size+1
cutfilename = path+'/'+str(filenum)+'.txt'
print cutfilename,linenum
linecache.clearcache()
line = linecache.getline(cutfilename,linenum)
linecache.clearcache()
data = json.loads(line)
return line
#test cutfile
#c = Cut()
#c.cutfileWithoutCut(Global.cutnews_origin_dir,Global.content_dir,Global.filesize)
#c.cutfile(Global.cutnews_dir,Global.content_dir,Global.filesize)
#test getRow
#c = Cut()
#c.getRow(200,Global.cutnews_dir,Global.filesize)
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def load_module(self, fullname):
if self.mod is None:
self.mod = mod = imp.new_module(fullname)
else:
mod = self.mod
mod.__file__ = '<%s>' % self.name
mod.__loader__ = self
mod.__project__ = self.project
mod.__package__ = ''
code = self.get_code(fullname)
six.exec_(code, mod.__dict__)
linecache.clearcache()
if sys.version_info[:2] == (3, 3):
sys.modules[fullname] = mod
return mod
def write_text(self, stream):
if not path.exists(self.filename):
stream.write("ERROR: %s\n" % self.filename)
return
stream.write("File: %s\n" % self.filename)
stream.write("Name: %s\n" % self.name)
stream.write("Total time: %g [sec]\n" % self.total_time)
linecache.clearcache()
lines = linecache.getlines(self.filename)
if self.name != "<module>":
lines = inspect.getblock(lines[self.firstlineno - 1:])
template = '%6s %9s %12s %-s'
header = template % ("Line", "Hits", "Time", "Code")
stream.write(header)
stream.write("\n")
stream.write("=" * len(header))
stream.write("\n")
d = {}
for i, code in zip(itertools.count(self.firstlineno), lines):
timing = self.timings.get(i)
if timing is None:
d[i] = {
"hits": "",
"time": "",
"code": code
}
else:
d[i] = {
"hits": timing.n_hits,
"time": timing.total_time,
"code": code
}
for i in sorted(d.keys()):
r = d[i]
stream.write(template % (i, r["hits"], r["time"], r["code"]))
stream.write("\n")
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info and linecache
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def setUp(self):
linecache.clearcache()
zipimport._zip_directory_cache.clear()
self.path = sys.path[:]
self.meta_path = sys.meta_path[:]
self.path_hooks = sys.path_hooks[:]
sys.path_importer_cache.clear()
def test_clearcache(self):
cached = []
for entry in TESTS:
filename = os.path.join(TEST_PATH, entry) + '.py'
cached.append(filename)
linecache.getline(filename, 1)
# Are all files cached?
cached_empty = [fn for fn in cached if fn not in linecache.cache]
self.assertEqual(cached_empty, [])
# Can we clear the cache?
linecache.clearcache()
cached_empty = [fn for fn in cached if fn in linecache.cache]
self.assertEqual(cached_empty, [])
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info and linecache
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def setUp(self):
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def test_clearcache(self):
cached = []
for entry in TESTS:
filename = os.path.join(TEST_PATH, entry) + '.py'
cached.append(filename)
linecache.getline(filename, 1)
# Are all files cached?
cached_empty = [fn for fn in cached if fn not in linecache.cache]
self.assertEqual(cached_empty, [])
# Can we clear the cache?
linecache.clearcache()
cached_empty = [fn for fn in cached if fn in linecache.cache]
self.assertEqual(cached_empty, [])
def test_memoryerror(self):
lines = linecache.getlines(FILENAME)
self.assertTrue(lines)
def raise_memoryerror(*args, **kwargs):
raise MemoryError
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines2 = linecache.getlines(FILENAME)
self.assertEqual(lines2, lines)
linecache.clearcache()
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines3 = linecache.getlines(FILENAME)
self.assertEqual(lines3, [])
self.assertEqual(linecache.getlines(FILENAME), lines)
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info and linecache
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
test_zipimport_support.py 文件源码
项目:python2-tracer
作者: extremecoders-re
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def setUp(self):
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def test_clearcache(self):
cached = []
for entry in TESTS:
filename = os.path.join(TEST_PATH, entry) + '.py'
cached.append(filename)
linecache.getline(filename, 1)
# Are all files cached?
cached_empty = [fn for fn in cached if fn not in linecache.cache]
self.assertEqual(cached_empty, [])
# Can we clear the cache?
linecache.clearcache()
cached_empty = [fn for fn in cached if fn in linecache.cache]
self.assertEqual(cached_empty, [])
def test_memoryerror(self):
lines = linecache.getlines(FILENAME)
self.assertTrue(lines)
def raise_memoryerror(*args, **kwargs):
raise MemoryError
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines2 = linecache.getlines(FILENAME)
self.assertEqual(lines2, lines)
linecache.clearcache()
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines3 = linecache.getlines(FILENAME)
self.assertEqual(lines3, [])
self.assertEqual(linecache.getlines(FILENAME), lines)
def _parse_metadata(rootdir, for_yaml, index):
origcwd = os.getcwd()
os.chdir(rootdir)
logger.debug("Parsing metadata:")
for f in for_yaml:
# Make the path to the file relative to the root directory
#f = os.path.relpath(f, rootdir)
logger.debug("Current file:")
logger.debug(f)
#only if there is more than the backbone.
if for_yaml[f]['start'] != '':
logger.debug("start: " + for_yaml[f]['start'])
logger.debug("stop: " + for_yaml[f]['stop'])
y = ''
for i in range(
int(for_yaml[f]['start']),
int(for_yaml[f]['stop'])
):
y = y + linecache.getline(f, i)
logger.debug("y: " + str(y))
metadata = yaml.safe_load(y)
#write the metadata to the index.
for item in metadata:
index['files'][f][item] = metadata[item]
linecache.clearcache()
os.chdir(origcwd)
logger.debug("Parsing metadata: Done.")
return index
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info and linecache
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def setUp(self):
linecache.clearcache()
zipimport._zip_directory_cache.clear()
self.path = sys.path[:]
self.meta_path = sys.meta_path[:]
self.path_hooks = sys.path_hooks[:]
sys.path_importer_cache.clear()
def test_clearcache(self):
cached = []
for entry in TESTS:
filename = os.path.join(TEST_PATH, entry) + '.py'
cached.append(filename)
linecache.getline(filename, 1)
# Are all files cached?
cached_empty = [fn for fn in cached if fn not in linecache.cache]
self.assertEqual(cached_empty, [])
# Can we clear the cache?
linecache.clearcache()
cached_empty = [fn for fn in cached if fn in linecache.cache]
self.assertEqual(cached_empty, [])
def __BuildFromException(self, site, type , value, tb):
if debugging:
import linecache
linecache.clearcache()
try:
if issubclass(type, SyntaxError):
self._BuildFromSyntaxError(site, value, tb)
else:
self._BuildFromOther(site, type, value, tb)
except: # Error extracting traceback info!!!
traceback.print_exc()
# re-raise.
raise
def GetActiveFileName(bAutoSave = 1):
"""Gets the file name for the active frame, saving it if necessary.
Returns None if it cant be found, or raises KeyboardInterrupt.
"""
pathName = None
active = GetActiveView()
if active is None:
return None
try:
doc = active.GetDocument()
pathName = doc.GetPathName()
if bAutoSave and \
(len(pathName)>0 or \
doc.GetTitle()[:8]=="Untitled" or \
doc.GetTitle()[:6]=="Script"): # if not a special purpose window
if doc.IsModified():
try:
doc.OnSaveDocument(pathName)
pathName = doc.GetPathName()
# clear the linecache buffer
linecache.clearcache()
except win32ui.error:
raise KeyboardInterrupt
except (win32ui.error, AttributeError):
pass
if not pathName:
return None
return pathName
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes_type),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()
def generate(self, **kwargs):
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
"squeeze": escape.squeeze,
"linkify": escape.linkify,
"datetime": datetime,
"_tt_utf8": escape.utf8, # for internal use
"_tt_string_types": (unicode_type, bytes),
# __name__ and __loader__ allow the traceback mechanism to find
# the generated source code.
"__name__": self.name.replace('.', '_'),
"__loader__": ObjectDict(get_source=lambda name: self.code),
}
namespace.update(self.namespace)
namespace.update(kwargs)
exec_in(self.compiled, namespace)
execute = namespace["_tt_execute"]
# Clear the traceback module's cache of source data now that
# we've generated a new template (mainly for this module's
# unittests, where different tests reuse the same name).
linecache.clearcache()
return execute()