本文整理汇总了Python中os.path.getmtime函数的典型用法代码示例。如果您正苦于以下问题:Python getmtime函数的具体用法?Python getmtime怎么用?Python getmtime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getmtime函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: needs_update
def needs_update(target, dependencies):
"""
Determine if the target is older than any of its dependencies.
:param target:
A filename for the target.
:param dependencies:
A sequence of dependency filenames.
"""
if not path.exists(target):
return True
target_time = path.getmtime(target)
for dependency in dependencies:
if isinstance(dependency, string_types):
filenames = [dependency]
elif isinstance(dependency, types.ModuleType):
filenames = _get_module_dependencies(dependency)
else:
raise TypeError("Unknown dependency type %s" % (type(dependency)))
for filename in filenames:
if path.getmtime(filename) > target_time:
return True
else:
return False
开发者ID:larsyencken,项目名称:cjktools,代码行数:27,代码来源:smart_cache.py
示例2: autocompile
def autocompile(ws, conf, env, **options):
"""Subcommand: autocompile -- automatically re-compiles when something in
content-dir has changed and parallel serving files."""
CONF_PY = './conf.py'
mtime = -1
cmtime = getmtime(CONF_PY)
while True:
ntime = max(
max(getmtime(e) for e in readers.filelist(conf['content_dir']) if utils.istext(e)),
max(getmtime(p) for p in readers.filelist(conf['layout_dir'])))
if mtime != ntime:
try:
compile(conf, env, **options)
except AcrylamidException as e:
log.fatal(e.args[0])
pass
event.reset()
mtime = ntime
if cmtime != getmtime(CONF_PY):
log.info(' * Restarting due to change in %s' % (CONF_PY))
# Kill the webserver
ws.shutdown()
# Force compilation since no template was changed
argv = sys.argv if options['force'] else sys.argv[:] + ["--force"]
# Restart acrylamid
os.execvp(sys.argv[0], argv)
time.sleep(1)
开发者ID:MeirKriheli,项目名称:acrylamid,代码行数:32,代码来源:commands.py
示例3: nb_renderer
def nb_renderer(full_path):
directory, base = split(full_path)
cache_file = join(directory, '.%s.html' % base)
if not current_app.config.get('DEBUG'):
try:
if isfile(cache_file) and getmtime(full_path) < getmtime(cache_file):
current_app.logger.debug('Using Cache File %s' % cache_file)
return raw_renderer(cache_file)
except:
current_app.logger.warn('There was an error reading from the cache file %s' % cache_file)
ex = HTMLExporter(extra_loaders=[current_app.jinja_env.loader],
template_file='wakari_notebook.html')
ex.environment.globals.update(current_app.jinja_env.globals)
current_app.update_template_context(ex.environment.globals)
ex.environment.globals.update(dirname=dirname(request.view_args['path']))
output, _ = ex.from_filename(full_path)
try:
with open(cache_file, 'w') as fd:
current_app.logger.debug('Writing Cache File %s' % cache_file)
fd.write(output.encode(errors='replace'))
except (OSError, IOError):
current_app.logger.warn('There was an error writing to the cache file %s' % cache_file)
try:
if isfile(cache_file): os.unlink(cache_file)
except OSError:
current_app.logger.warn('There was an error removing the cache file %s' % cache_file)
pass
return output
开发者ID:B-Rich,项目名称:wakari-app-viewer,代码行数:34,代码来源:renderer.py
示例4: init_chess_db
def init_chess_db(self):
""" Create/open polyglot .bin file with extra win/loss/draw stats
using chess_db parser from https://github.com/mcostalba/chess_db
"""
if chess_db_path is not None and self.path and self.size > 0:
try:
if self.progressbar is not None:
self.progressbar.set_text("Creating .bin index file...")
self.chess_db = Parser(engine=(chess_db_path, ))
self.chess_db.open(self.path)
bin_path = os.path.splitext(self.path)[0] + '.bin'
if not os.path.isfile(bin_path):
log.debug("No valid games found in %s" % self.path)
self.chess_db = None
elif getmtime(self.path) > getmtime(bin_path):
self.chess_db.make()
except OSError as err:
self.chess_db = None
log.warning("Failed to sart chess_db parser. OSError %s %s" % (err.errno, err.strerror))
except pexpect.TIMEOUT:
self.chess_db = None
log.warning("chess_db parser failed (pexpect.TIMEOUT)")
except pexpect.EOF:
self.chess_db = None
log.warning("chess_db parser failed (pexpect.EOF)")
开发者ID:bboutkov,项目名称:pychess,代码行数:25,代码来源:pgn.py
示例5: datread
def datread(self):
"""\
Reads in data from .dat or .npy file paths and if .dat is newer than .npy saves
it in .npy format for faster reading in future."""
for vals in self.files:
if vals['type'] == 'dat' and vals['dir'] == 'pull':
# self.datfileloc = vals['dir']
pth = vals['path']
pthnpy = pth.replace('.dat', '.npy', 1)
try:
print("""\
DAT File:\t{0}
DAT: time last modified:\t{2}
NPY File:\t{1}
NPY: time last modified:\t{3}""".format(pth, pthnpy, \
time.ctime(path.getmtime(pth)), \
time.ctime(path.getmtime(pthnpy))))
if path.getmtime(pth) <= path.getmtime(pthnpy):
print('DATFILE: is older than npy... Continue.\n')
else:
print('DATFILE: is newer than npy... Remaking.\n')
os.remove(pthnpy)
except OSError:
pass
if vals['dir'] == 'pull':
self.datcheck = True
self.path = pth
if path.exists(pthnpy):
self.dat = np.load(pthnpy)
else:
self.dat = np.loadtxt(pth)
np.save(pthnpy, self.dat)
开发者ID:slushecl,项目名称:dev,代码行数:32,代码来源:core.py
示例6: test_download_cached_file
def test_download_cached_file(self):
section = Section('default')
uut = Bear(section, {})
mock_url = 'https://test.com'
mock_text = """<html>
<p> lorem ipsum dolor</p>
</html>"""
filename = 'test.html'
file_location = join(uut.data_dir, filename)
with requests_mock.Mocker() as reqmock:
reqmock.get(mock_url, text=mock_text)
self.assertFalse(isfile(file_location))
expected_filename = file_location
result_filename = uut.download_cached_file(mock_url, filename)
self.assertTrue(isfile(join(file_location)))
self.assertEqual(result_filename, expected_filename)
expected_time = getmtime(file_location)
sleep(0.5)
result_filename = uut.download_cached_file(mock_url, filename)
self.assertEqual(result_filename, expected_filename)
result_time = getmtime(file_location)
self.assertEqual(result_time, expected_time)
开发者ID:arush0311,项目名称:coala,代码行数:25,代码来源:BearTest.py
示例7: comp
def comp (source_patch, target_patch):
from os import path, walk
from filecmp import cmp
# выходное сообщение о найденных отличиях
message = ''
path_f = []
tree = walk(source_patch)
for d, dirs, files in tree:
for f in files:
patch = path.join(d,f) # формирование адреса
path_f.append(patch) # добавление адреса в список
# перибираем адреса файлов из списка
for patch in path_f:
# выполняем сравнение файлов и в случае отличий получаем информацию о файлах
# проверяем существование файла
if not path.exists(patch.replace(source_patch, target_patch)):
message = message + 'Отсутствует целевой файл: '+ patch.replace(source_patch, target_patch)
# сверяем размеры исходного и целевого файла
elif path.getsize(patch.replace(source_patch, target_patch)) <> path.getsize(patch):
message = message + file_info(patch, patch.replace(source_patch, target_patch))
# дата последней модификации
elif path.getmtime(patch.replace(source_patch, target_patch)) <> path.getmtime(patch):
message = message + file_info(patch, patch.replace(source_patch, target_patch))
# сравниваем файлы
elif not cmp(patch.replace(source_patch, target_patch), patch):
message = message + file_info(patch, patch.replace(source_patch, target_patch))
return message
开发者ID:Concord82,项目名称:Sync_Servers,代码行数:27,代码来源:sync_disk.py
示例8: get_source
def get_source(self, environment, template):
"""Try and get the template from the given pseudo-pathname.
It uses, like the Jinja2 documentation example, the getmtime
function to know whether a template file had been changed
or not.
"""
if "/" not in template:
path = template.split(".")
# The first part of the path must be a bundle name
# The other parts are the hierarchy of directory after 'views'
bundle = path[0]
sub_hierarchy = "/".join(path[1:])
path = "bundles/" + bundle + "/views/" + sub_hierarchy + ".jj2"
else:
path = template
print(path)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with open(path, "r") as file:
source = file.read()
return source, path, lambda: mtime == getmtime(path)
开发者ID:Erwyn,项目名称:pa-poc2,代码行数:27,代码来源:loader.py
示例9: test_update_conf
def test_update_conf(self, default_config, show_notification):
conf_time_1 = path.getmtime(self.tmp.conf.join("config.py"))
out_file = self.tmp_output.join("out.log")
command_args = [
"-c", self.config_file,
"-r", "bash -c 'echo a | tee -a {}'".format(out_file),
"-d", unicode(self.tmp.src),
]
events = [
(self.tmp.conf, "config.py", "# some new data"),
(self.tmp.conf, "config.py", "# some new data"),
]
self._copy_default_config(default_config)
default_config.RUNNER_DELAY = -1
wm = WatchManager()
config = Config(watch_manager=wm, command_args=command_args)
handler = FileChangeHandler(config=config)
notifier = Notifier(wm, handler, timeout=1000)
notifier.loop(callback=partial(self._event_generator, events))
# There are some stupid race conditions (possibly due to the callbacks)
# Sleep time allows to execute all needed code
sleep(0.2)
conf_time_2 = path.getmtime(self.tmp.conf.join("config.py"))
self.assertNotEqual(conf_time_1, conf_time_2)
self.assertTrue(path.exists(out_file))
self.assertEqual(show_notification.call_count, 2)
开发者ID:mrfuxi,项目名称:testrunner,代码行数:32,代码来源:test_functional.py
示例10: get_preview
def get_preview(origpath, thumbnail=False, return_orientation=False):
# TODO when the rest is working go back to using crcs as the filename
p_type = 'thumbnails' if thumbnail else 'previews'
preview = join(
PREVIEWDIR, p_type, dirname(origpath)[1:], basename(origpath)+'.jpg')
try:
origmtime = getmtime(origpath)
prevmtime = getmtime(preview)
if prevmtime >= origmtime:
if not return_orientation:
return preview
else:
return (preview, orientations.get(preview))
except:
pass # The preview is not yet built
if blacklist.match(origpath, origmtime=origmtime):
raise PreviewError
try:
(preview, orientation) = build_preview(origpath, preview, thumbnail)
except:
blacklist.add(origpath)
raise PreviewError
orientations.set(preview, orientation)
if not return_orientation:
return preview
else:
return (preview, orientation)
开发者ID:jtoledo1974,项目名称:raw2jpeg,代码行数:32,代码来源:previewcache.py
示例11: _should_recompile
def _should_recompile(auxdir, parser, modules, compiler):
"""Determines whether the fpy_auxiliary module should be rewritten and recompiled.
"""
from os import path
from shutil import copy
recompile = False
for modulename in modules:
module = parser.modules[modulename]
auxpath = path.join(auxdir, path.split(module.filepath)[1])
if not path.isfile(auxpath):
copy(module.filepath, auxdir)
recompile = True
else:
fmtime = path.getmtime(module.filepath)
xmtime = path.getmtime(auxpath)
if xmtime < fmtime:
recompile = True
copy(module.filepath, auxdir)
#Also check the version numbers of the template fpy_auxiliary.f90 and the one present
#in our directory (if it exists).
fpyaux = path.join(auxdir, "fpy_auxiliary.f90")
if path.isfile(fpyaux):
from fortpy.testing.compilers import template_version, get_fortpy_version
tversion = template_version(compiler, "fpy_auxiliary.f90")
xversion = get_fortpy_version(compiler, fpyaux)
recompile = recompile or (xversion != tversion)
else:
recompile = True
return recompile
开发者ID:rosenbrockc,项目名称:fortpy,代码行数:32,代码来源:auxiliary.py
示例12: createDict
def createDict(path, root={}):
pathList = listdir(path)
for i, item in enumerate(pathList):
file_path = path_join(path, item)
if item not in ignore_dir and exists(file_path):
if isdir(file_path):
if not root.get(item, False):
root[item] = {"type": "dir", "files": {}}
createDict(file_path, root[item]["files"])
else:
if not root.get(item, False):
log("new file " + file_path)
root[item] = {"type": "file",
"file_size": getsize(file_path),
"mtime": getmtime(file_path),
"ctime": getctime(file_path),
"md5": md5(file_path),
"sha256": sha256(file_path)}
else:
if root[item]["mtime"] != getmtime(file_path):
log("rehashing " + file_path)
root[item] = {"type": "file",
"file_size": getsize(file_path),
"mtime": getmtime(file_path),
"ctime": getctime(file_path),
"md5": md5(file_path),
"sha256": sha256(file_path)}
return root
开发者ID:Yexiaoxing,项目名称:smart-mirrors,代码行数:30,代码来源:fileListGenerator.py
示例13: is_actual_problem
def is_actual_problem(problem_id):
# This is a very paranoid function
global _cached_problem_ids
assert _id_rx.match(problem_id), problem_id
def sanity_check(ids):
assert len(ids) == 1420 + 200 + 200
assert all(_id_rx.match(id) for id in ids)
if _cached_problem_ids is None:
if not os_path.exists(MYPROBLEMS_FILE):
# regenerate problems file
update_myproblems_file()
if (not os_path.exists(CACHED_PROBLEM_IDS_FILE) or
os_path.getmtime(CACHED_PROBLEM_IDS_FILE) < os_path.getmtime(MYPROBLEMS_FILE)):
# regenerate CACHED_PROBLEM_IDS_FILE
problems = load_problems()
ids = frozenset(problem.id for problem in problems)
sanity_check(ids)
with open(CACHED_PROBLEM_IDS_FILE, 'wb') as f:
pickle.dump(ids, f)
else:
with open(CACHED_PROBLEM_IDS_FILE, 'rb') as f:
ids = pickle.load(f)
sanity_check(ids)
_cached_problem_ids = ids
return problem_id in _cached_problem_ids
开发者ID:Vlad-Shcherbina,项目名称:icfpc2013-tbd,代码行数:29,代码来源:statistics.py
示例14: resolve
def resolve(uri):
"""Check whether any referenced template has changed -- recursively."""
self.used.add(uri)
if uri in self.resolved:
return self.resolved[uri]
filename = posixpath.normpath(posixpath.join(self.directories[0], uri))
p = self.modulename_callable(filename, uri)
modified = getmtime(filename) > getmtime(p) if isfile(p) else True
if modified:
self.resolved[uri] = True
return True
with io.open(filename) as fp:
source = fp.read()
for match in self.inherits.finditer(source):
if resolve(match.group(1)):
return True
for match in self.includes.finditer(source):
if resolve(match.group(1)):
return True
return False
开发者ID:maphew,项目名称:acrylamid,代码行数:28,代码来源:mako.py
示例15: test_download_cached_file
def test_download_cached_file(self):
mock_url = 'https://test.com'
mock_text = """<html>
<p> lorem impsum dolor</p>
</html>"""
filename = self.filename
file_location = self.file_location
with freeze_time('2017-01-01') as frozen_datetime:
with requests_mock.Mocker() as reqmock:
reqmock.get(mock_url, text=mock_text)
self.assertFalse(isfile(file_location))
expected_filename = file_location
result_filename = self.uut.download_cached_file(mock_url,
filename)
self.assertTrue(isfile(join(file_location)))
self.assertEqual(result_filename, expected_filename)
expected_time = getmtime(file_location)
frozen_datetime.tick(delta=datetime.timedelta(seconds=0.5))
result_filename = self.uut.download_cached_file(mock_url,
filename)
self.assertEqual(result_filename, expected_filename)
result_time = getmtime(file_location)
self.assertEqual(result_time, expected_time)
开发者ID:Anmolbansal1,项目名称:coala,代码行数:26,代码来源:BearTest.py
示例16: get_cached_data
def get_cached_data():
"""Get current data and update cache."""
cache_read = False
typesetting_data = {}
try:
with open(cache_filename, "rb") as storage:
typesetting_data = load(storage)
cache_read = True
cache_data_outdated = getmtime(file_path) < getmtime(cache_filename) > getmtime(filepath)
# Write new cache data if the current data does not contain
# the necessary up to date information - This might be the case if
# only `texparser` has written to the cache file
if "engine" not in typesetting_data or cache_data_outdated:
raise Exception()
except:
# Get data and save it in the cache
packages = find_tex_packages(filename, ignore_warnings)
engine = construct_engine_command(typesetting_directives, tm_engine, packages)
synctex = not (bool(call("{} --help | grep -q synctex".format(engine), shell=True)))
typesetting_data.update({"engine": engine, "packages": packages, "synctex": synctex})
if not cache_read:
typesetting_data["files_with_guttermarks"] = {filename}
try:
with open(cache_filename, "wb") as storage:
dump(typesetting_data, storage)
except:
print('<p class="warning"> Could not write cache file!</p>')
return typesetting_data
开发者ID:DOFfactory,项目名称:latex.tmbundle,代码行数:34,代码来源:texmate.py
示例17: wrapped
def wrapped(image, new_width, new_height, *args, **kwargs):
save_to = kwargs.pop('save_to', None)
force = kwargs.pop('force', False)
# TODO: Instead of passing the image object to the save_to()
# call, we could simply pass the source filename. This would
# allow us to move this code further below so that we only
# open the image file once the timestamp comparison determined
# that we actually have to.
if isinstance(image, basestring):
source_filename = image
image = Image.open(image)
else:
source_filename = None
force = True # no filename => detection disabled
thumb_filename = None
if save_to:
thumb_filename = save_to(image, new_width, new_height) \
if callable(save_to) \
else save_to
if save_to and not force:
if path.exists(thumb_filename):
if path.getmtime(source_filename) <= path.getmtime(thumb_filename):
return image
result = f(image, new_width, new_height, *args, **kwargs)
if result and save_to:
result.save(thumb_filename, image.format)
return result
开发者ID:miracle2k,项目名称:feedplatform,代码行数:32,代码来源:_thumbnail.py
示例18: ReadStatusFile
def ReadStatusFile(path, variables):
# As long as the old-format .status files are authoritative, just
# create the converted version on demand and cache it to speed up
# subsequent runs.
if path.endswith(".status"):
newpath = path + "2"
if not exists(newpath) or getmtime(newpath) < getmtime(path):
print "Converting status file."
converted = old_statusfile.ConvertNotation(path).GetOutput()
with open(newpath, 'w') as f:
f.write(converted)
path = newpath
with open(path) as f:
global KEYWORDS
contents = eval(f.read(), KEYWORDS)
rules = {}
wildcards = {}
variables.update(VARIABLES)
for section in contents:
assert type(section) == list
assert len(section) == 2
if not eval(section[0], variables): continue
section = section[1]
assert type(section) == dict
for rule in section:
assert type(rule) == str
if rule[-1] == '*':
_ParseOutcomeList(rule, section[rule], wildcards, variables)
else:
_ParseOutcomeList(rule, section[rule], rules, variables)
return rules, wildcards
开发者ID:AKIo0O,项目名称:node,代码行数:33,代码来源:statusfile.py
示例19: recreate_tox
def recreate_tox(self, environments):
"""Recreate tox-environments.
:param environments: Which environments to recreate.
:type environments: list
:rtype: list
"""
req_txt = self.get_filename_setup('requirements.txt')
req_dev_txt = self.get_filename_setup('requirements-dev.txt')
req_mtimes = list()
env_mtimes = list()
if path.exists(req_txt):
req_mtimes.append(path.getmtime(req_txt))
if path.exists(req_dev_txt):
req_mtimes.append(path.getmtime(req_dev_txt))
for environment in environments:
env_path = self.get_filename_setup('.tox/' + environment)
if path.exists(env_path):
env_mtimes.append(path.getmtime(env_path))
if len(env_mtimes) and max(req_mtimes) > min(env_mtimes):
run('tox', '--recreate', '--notest')
开发者ID:CorverDevelopment,项目名称:Assemble,代码行数:28,代码来源:assemble.py
示例20: get_hashes
def get_hashes(partition_dir, recalculate=None, do_listdir=False,
reclaim_age=ONE_WEEK):
"""
Get a list of hashes for the suffix dir. do_listdir causes it to mistrust
the hash cache for suffix existence at the (unexpectedly high) cost of a
listdir. reclaim_age is just passed on to hash_suffix.
:param partition_dir: absolute path of partition to get hashes for
:param recalculate: list of suffixes which should be recalculated when got
:param do_listdir: force existence check for all hashes in the partition
:param reclaim_age: age at which to remove tombstones
:returns: tuple of (number of suffix dirs hashed, dictionary of hashes)
"""
hashed = 0
hashes_file = join(partition_dir, HASH_FILE)
modified = False
force_rewrite = False
hashes = {}
mtime = -1
if recalculate is None:
recalculate = []
try:
with open(hashes_file, 'rb') as fp:
hashes = pickle.load(fp)
mtime = getmtime(hashes_file)
except Exception:
do_listdir = True
force_rewrite = True
if do_listdir:
for suff in os.listdir(partition_dir):
if len(suff) == 3:
hashes.setdefault(suff, None)
modified = True
hashes.update((hash_, None) for hash_ in recalculate)
for suffix, hash_ in hashes.items():
if not hash_:
suffix_dir = join(partition_dir, suffix)
try:
hashes[suffix] = hash_suffix(suffix_dir, reclaim_age)
hashed += 1
except PathNotDir:
del hashes[suffix]
except OSError:
logging.exception(_('Error hashing suffix'))
modified = True
if modified:
with lock_path(partition_dir):
if force_rewrite or not exists(hashes_file) or \
getmtime(hashes_file) == mtime:
write_pickle(
hashes, hashes_file, partition_dir, PICKLE_PROTOCOL)
return hashed, hashes
return get_hashes(partition_dir, recalculate, do_listdir,
reclaim_age)
else:
return hashed, hashes
开发者ID:Dieterbe,项目名称:swift,代码行数:60,代码来源:diskfile.py
注:本文中的os.path.getmtime函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论