本文整理汇总了Python中miro.fileutil.expand_filename函数的典型用法代码示例。如果您正苦于以下问题:Python expand_filename函数的具体用法?Python expand_filename怎么用?Python expand_filename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expand_filename函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_movies_directory_gone
def is_movies_directory_gone():
"""Checks to see if the MOVIES_DIRECTORY exists.
Returns True if yes, False if no.
"""
movies_dir = fileutil.expand_filename(app.config.get(prefs.MOVIES_DIRECTORY))
if not movies_dir.endswith(os.path.sep):
movies_dir += os.path.sep
logging.info("Checking movies directory %r...", movies_dir)
try:
if os.path.exists(movies_dir):
contents = os.listdir(movies_dir)
if contents:
# there's something inside the directory consider it
# present (even if all our items are missing).
return False
except OSError:
# we can't access the directory--treat it as if it's gone.
logging.info("Can't access directory.")
return True
# at this point either there's no movies_dir or there is an empty
# movies_dir. we check to see if we think something is downloaded.
for downloader_ in downloader.RemoteDownloader.make_view():
if ((downloader_.is_finished()
and downloader_.get_filename().startswith(movies_dir))):
# we think something is downloaded, so it seems like the
# movies directory is gone.
logging.info("Directory there, but missing files.")
return True
# we have no content, so everything's fine.
return False
示例2: get_favicon_path
def get_favicon_path(self):
"""Returns the path to the favicon file. It's either the favicon of
the site or the default icon image.
"""
if self.icon_cache and self.icon_cache.get_filename():
return fileutil.expand_filename(self.icon_cache.get_filename())
return resources.path("images/icon-site.png")
示例3: check_movies_gone
def check_movies_gone():
"""Checks to see if the movies directory is gone.
"""
callback = lambda: eventloop.add_urgent_call(fix_movies_gone,
"fix movies gone")
if is_movies_directory_gone():
logging.info("Movies directory is gone -- calling handler.")
_movies_directory_gone_handler(callback)
return
movies_dir = fileutil.expand_filename(app.config.get(prefs.MOVIES_DIRECTORY))
# if the directory doesn't exist, create it.
if not os.path.exists(movies_dir):
try:
os.makedirs(movies_dir)
except OSError:
logging.info("Movies directory can't be created -- calling handler")
# FIXME - this isn't technically correct, but it's probably
# close enough that a user can fix the issue and Miro can
# run happily.
_movies_directory_gone_handler(callback)
return
# make sure the directory is writeable
if not os.access(movies_dir, os.W_OK):
_movies_directory_gone_handler(callback)
return
eventloop.add_urgent_call(finish_backend_startup, "reconnect downloaders")
示例4: next_free_filename
def next_free_filename(name):
"""Finds a filename that's unused and similar the the file we want
to download and returns an open file handle to it.
"""
check_f(name)
mask = os.O_CREAT | os.O_EXCL | os.O_RDWR
# Try with the name supplied.
try:
fd = os.open(expand_filename(name), mask)
fp = os.fdopen(fd, 'wb')
return expand_filename(name), fp
except OSError:
pass
# Boh boh ... did't work. Let's try to create a variant name and
# open that instead.
parts = name.split('.')
count = 1
if len(parts) == 1:
newname = "%s.%s" % (name, count)
while True:
try:
fd = os.open(expand_filename(newname), mask)
fp = os.fdopen(fd, 'wb')
break
except OSError:
count += 1
newname = "%s.%s" % (name, count)
continue
else:
parts[-1:-1] = [str(count)]
newname = '.'.join(parts)
while True:
try:
fd = os.open(expand_filename(newname), mask)
fp = os.fdopen(fd, 'wb')
break
except OSError:
count += 1
parts[-2] = str(count)
newname = '.'.join(parts)
continue
return (expand_filename(newname), fp)
示例5: clear_icon_cache_orphans
def clear_icon_cache_orphans():
# delete icon_cache rows from the database with no associated
# item/feed/guide.
removed_objs = []
for ic in iconcache.IconCache.orphaned_view():
logging.warn("No object for IconCache: %s. Discarding", ic)
ic.remove()
removed_objs.append(str(ic.url))
if removed_objs:
databaselog.info("Removed IconCache objects without an associated "
"db object: %s", ','.join(removed_objs))
yield None
# delete files in the icon cache directory that don't belong to IconCache
# objects.
cachedir = fileutil.expand_filename(app.config.get(
prefs.ICON_CACHE_DIRECTORY))
if not os.path.isdir(cachedir):
return
existingFiles = [os.path.normcase(os.path.join(cachedir, f))
for f in os.listdir(cachedir)]
yield None
knownIcons = iconcache.IconCache.all_filenames()
yield None
knownIcons = [ os.path.normcase(fileutil.expand_filename(path)) for path in
knownIcons]
yield None
for filename in existingFiles:
if (os.path.exists(filename)
and os.path.basename(filename)[0] != '.'
and os.path.basename(filename) != 'extracted'
and not filename in knownIcons):
try:
os.remove(filename)
except OSError:
pass
yield None
示例6: get_available_bytes_for_movies
def get_available_bytes_for_movies():
moviesDir = fileutil.expand_filename(app.config.get(prefs.MOVIES_DIRECTORY))
freeSpace = ctypes.c_ulonglong(0)
availableSpace = ctypes.c_ulonglong(0)
totalSpace = ctypes.c_ulonglong(0)
rv = ctypes.windll.kernel32.GetDiskFreeSpaceExW(unicode(moviesDir),
ctypes.byref(availableSpace), ctypes.byref(totalSpace),
ctypes.byref(freeSpace))
if rv == 0:
print "GetDiskFreeSpaceExW failed, returning bogus value!"
return 100 * 1024 * 1024 * 1024
return availableSpace.value
示例7: delete
def delete(self):
if self.filename is None:
return
try:
fileutil.delete(self.filename)
except OSError:
logging.exception("Error deleting downloaded file: %s",
to_uni(self.filename))
parent = os.path.join(fileutil.expand_filename(self.filename),
os.path.pardir)
parent = os.path.normpath(parent)
movies_dir = fileutil.expand_filename(app.config.get(prefs.MOVIES_DIRECTORY))
if ((os.path.exists(parent) and os.path.exists(movies_dir)
and not samefile(parent, movies_dir)
and len(os.listdir(parent)) == 0)):
try:
os.rmdir(parent)
except OSError:
logging.exception("Error deleting empty download directory: %s",
to_uni(parent))
self.filename = None
示例8: next_free_filename
def next_free_filename(name):
"""Finds a filename that's unused and similar the the file we want
to download and returns an open file handle to it.
"""
check_f(name)
mask = os.O_CREAT | os.O_EXCL | os.O_RDWR
# On Windows we need to pass in O_BINARY, fdopen() even with 'b'
# specified is not sufficient.
if sys.platform == 'win32':
mask |= os.O_BINARY
candidates = next_free_filename_candidates(name)
while True:
# Try with the name supplied.
newname = candidates.next()
try:
fd = os.open(expand_filename(newname), mask)
fp = os.fdopen(fd, 'wb')
return expand_filename(newname), fp
except OSError:
continue
return (expand_filename(newname), fp)
示例9: _start_torrent
def _start_torrent(self):
try:
torrent_info = lt.torrent_info(lt.bdecode(self.metainfo))
duplicate = TORRENT_SESSION.find_duplicate_torrent(torrent_info)
if duplicate is not None:
c = command.DuplicateTorrent(daemon.LAST_DAEMON,
duplicate.dlid, self.dlid)
c.send()
return
self.totalSize = torrent_info.total_size()
if self.firstTime and not self.accept_download_size(self.totalSize):
self.handle_error(
_("Not enough disk space"),
_("%(amount)s MB required to store this video",
{"amount": self.totalSize / (2 ** 20)})
)
return
save_path = os.path.dirname(fileutil.expand_filename(self.filename))
if self.fastResumeData:
self.torrent = TORRENT_SESSION.session.add_torrent(
torrent_info, save_path, lt.bdecode(self.fastResumeData),
lt.storage_mode_t.storage_mode_allocate)
self.torrent.resume()
else:
self.torrent = TORRENT_SESSION.session.add_torrent(
torrent_info, save_path, None,
lt.storage_mode_t.storage_mode_allocate)
try:
if (lt.version_major, lt.version_minor) > (0, 13):
logging.debug(
"setting libtorrent auto_managed to False")
self.torrent.auto_managed(False)
except AttributeError:
logging.warning("libtorrent module doesn't have "
"version_major or version_minor")
except (SystemExit, KeyboardInterrupt):
raise
except:
self.handle_error(_('BitTorrent failure'),
_('BitTorrent failed to startup'))
logging.exception("Exception thrown in _start_torrent")
else:
TORRENT_SESSION.add_torrent(self)
示例10: check_movies_gone
def check_movies_gone(self, check_unmounted=True):
"""Checks to see if the movies directory is gone.
"""
movies_dir = fileutil.expand_filename(app.config.get(
prefs.MOVIES_DIRECTORY))
movies_dir = filename_to_unicode(movies_dir)
# if the directory doesn't exist, create it.
if (not os.path.exists(movies_dir) and
should_create_movies_directory(movies_dir)):
try:
fileutil.makedirs(movies_dir)
except OSError:
logging.info("Movies directory can't be created -- calling handler")
# FIXME - this isn't technically correct, but it's probably
# close enough that a user can fix the issue and Miro can
# run happily.
msg = _("Permissions error: %(appname)s couldn't "
"create the folder.",
{"appname": app.config.get(prefs.SHORT_APP_NAME)})
self.movies_directory_gone_handler(msg, movies_dir)
return
# make sure the directory is writeable
if not os.access(movies_dir, os.W_OK):
logging.info("Can't write to movies directory -- calling handler")
msg = _("Permissions error: %(appname)s can't "
"write to the folder.",
{"appname": app.config.get(prefs.SHORT_APP_NAME)})
self.movies_directory_gone_handler(msg, movies_dir)
return
# make sure that the directory is populated if we've downloaded stuff to
# it
if check_unmounted and check_movies_directory_unmounted():
logging.info("Movies directory is gone -- calling handler.")
msg = _("The folder contains no files: "
"is it on a drive that's disconnected?")
self.movies_directory_gone_handler(msg, movies_dir,
allow_continue=True)
return
self.all_checks_done()
示例11: _getConfigFile
def _getConfigFile():
return fileutil.expand_filename(os.path.join(_getSupportDirectory(), "preferences.bin"))
示例12: get
def get(descriptor):
if descriptor == prefs.MOVIES_DIRECTORY:
return os.path.join(specialfolders.baseMoviesDirectory, app.configfile['shortAppName'])
elif descriptor == prefs.NON_VIDEO_DIRECTORY:
return specialfolders.nonVideoDirectory
elif descriptor == prefs.GETTEXT_PATHNAME:
return resources.path("locale")
elif descriptor == prefs.SUPPORT_DIRECTORY:
return fileutil.expand_filename(_getSupportDirectory())
elif descriptor == prefs.ICON_CACHE_DIRECTORY:
return os.path.join(_getSupportDirectory(), 'icon-cache')
elif descriptor == prefs.SQLITE_PATHNAME:
path = get(prefs.SUPPORT_DIRECTORY)
return os.path.join(path, 'sqlitedb')
elif descriptor == prefs.LOG_PATHNAME:
if u3info.u3_active:
directory = u3info.app_data_path
else:
directory = tempfile.gettempdir()
return os.path.join(directory,
('%s.log' % app.configfile['shortAppName']))
elif descriptor == prefs.DOWNLOADER_LOG_PATHNAME:
if u3info.u3_active:
directory = u3info.app_data_path
else:
directory = tempfile.gettempdir()
return os.path.join(directory,
('%s-downloader.log' % app.configfile['shortAppName']))
elif descriptor == prefs.RUN_AT_STARTUP:
import logging
# We use the legacy startup registry key, so legacy versions
# of Windows have a chance
# http://support.microsoft.com/?kbid=270035
try:
folder = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
"Software\Microsoft\Windows\CurrentVersion\Run")
except WindowsError, e:
# 2 indicates that the key doesn't exist yet, so
# RUN_AT_STARTUP is clearly False
if e.errno == 2:
logging.exception("=== windowserror kicked up at open key ===")
return False
raise
long_app_name = app.configfile['longAppName']
count = 0
while True:
try:
name, val, type_ = _winreg.EnumValue(folder, count)
count += 1
if name == long_app_name:
return True
except WindowsError, e:
# 22 indicates there are no more items in this folder to
# iterate through.
if e.errno == 22:
return False
else:
raise
示例13: _calc_program_info
def _calc_program_info(self):
videopath = fileutil.expand_filename(self.video_path)
thumbnailpath = fileutil.expand_filename(self.thumbnail_path)
command_line, env = movie_data_program_info(videopath, thumbnailpath)
return command_line, env
示例14: _get_item_dict
def _get_item_dict(self, item):
"""Take an item and convert all elements into a dictionary
return a dictionary of item elements
"""
def compatibleGraphics(filename):
if filename:
(dirName, fileName) = os.path.split(filename)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
if not fileExtension[1:] in [u"png", u"jpg", u"bmp", u"gif"]:
return u''
else:
return filename
else:
return u''
def useImageMagick(screenshot):
""" Using ImageMagick's utility 'identify'. Decide whether the screen shot is worth using.
>>> useImageMagick('identify screenshot.jpg')
>>> Example returned information "rose.jpg JPEG 640x480 DirectClass 87kb 0.050u 0:01"
>>> u'' if the screenshot quality is too low
>>> screenshot if the quality is good enough to use
"""
if not self.imagemagick: # If imagemagick is not installed do not bother checking
return u''
width_height = re.compile(u'''^(.+?)[ ]\[?([0-9]+)x([0-9]+)[^\\/]*$''', re.UNICODE)
p = subprocess.Popen(u'identify "%s"' % (screenshot), shell=True, bufsize=4096, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
response = p.stdout.readline()
if response:
match = width_height.match(response)
if match:
dummy, width, height = match.groups()
width, height = int(width), int(height)
if width >= 320:
return screenshot
return u''
else:
return u''
return screenshot
# end useImageMagick()
item_icon_filename = None
channel_icon = None
if item.getFeed():
channel_icon = fileutil.expand_filename(item.getFeed().iconCache.get_filename())
if item.iconCache and item.iconCache.filename:
item_icon_filename = item.iconCache.filename
# Conform to maximum length for MythTV database fields title and subtitle
maximum_length = 128
channel_title = item.get_channel_title(True).replace(u'/',u'-')
if channel_title:
if len(channel_title) > maximum_length:
channel_title = channel_title[:maximum_length]
channel_title = channel_title.replace(u'"', u'') # These characters mess with filenames
title = item.get_title().replace(u'/',u'-')
if title:
if len(title) > maximum_length:
title = title[:maximum_length]
title = title.replace(u'"', u'') # These characters mess with filenames
title = title.replace(u"'", u'') # These characters mess with filenames
item_dict = {u'feed_id': item.feed_id, u'parent_id': item.parent_id, u'isContainerItem': item.isContainerItem, u'isVideo': item.isVideo, u'seen': item.seen, u'autoDownloaded': item.autoDownloaded, u'pendingManualDL': item.pendingManualDL, u'downloadedTime': item.downloadedTime, u'watchedTime': item.watchedTime, u'pendingReason': item.pendingReason, u'title': title, u'expired': item.expired, u'keep': item.keep, u'videoFilename': item.get_filename(), u'eligibleForAutoDownload': item.eligibleForAutoDownload, u'duration': item.duration, u'screenshot': item.screenshot, u'resized_screenshots': item.resized_screenshots, u'resumeTime': item.resumeTime, u'channelTitle': channel_title, u'description': item.get_description(), u'size': item._get_size(), u'releasedate': item.get_release_date_obj(), u'length': item.get_duration_value(), u'channel_icon': channel_icon, u'item_icon': item_icon_filename, u'inetref': u'', u'season': 0, u'episode': 0,}
if not item_dict[u'screenshot']:
if item_dict[u'item_icon']:
item_dict[u'screenshot'] = useImageMagick(item_dict[u'item_icon'])
for key in [u'screenshot', u'channel_icon', u'item_icon']:
if item_dict[key]:
item_dict[key] = compatibleGraphics(item_dict[key])
#if self.verbose:
# if item_dict[key]:
# print "item (%s - %s) %s (%s)" % (channel_title, title, key, item_dict[key])
# else:
# print "item (%s - %s) does NOT have a %s" % (channel_title, title, key)
#print item_dict
return item_dict
示例15: _get_config_file
def _get_config_file():
return fileutil.expand_filename(
os.path.join(_get_support_directory(), "preferences.bin"))