本文整理汇总了Python中fs.osfs.OSFS.open方法的典型用法代码示例。如果您正苦于以下问题:Python OSFS.open方法的具体用法?Python OSFS.open怎么用?Python OSFS.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fs.osfs.OSFS
的用法示例。
在下文中一共展示了OSFS.open方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def main():
parser = argparse.ArgumentParser(description='Create free editor.slf')
parser.add_argument('original', help="Original editor.slf")
parser.add_argument(
'-o',
'--output',
default='build/editor.slf',
help="Where to store the created slf file"
)
args = parser.parse_args()
if not os.path.exists(os.path.dirname(args.output)):
os.makedirs(os.path.dirname(args.output))
target_fs = BufferedSlfFS()
replacement_fs = OSFS('editor')
with open(args.original, 'rb') as source_file:
source_fs = SlfFS(source_file)
target_fs.library_name = source_fs.library_name
target_fs.library_path = source_fs.library_path
target_fs.version = source_fs.version
target_fs.sort = source_fs.sort
for directory in source_fs.walkdirs():
if directory == '/':
continue
target_fs.makedir(directory)
for file in source_fs.walkfiles():
base_name, _ = os.path.splitext(file)
with source_fs.open(file, 'rb') as source, target_fs.open(file, 'wb') as target:
ja2_images = load_8bit_sti(source)
replacement_path = base_name + '.gif'
replacement_file_exists = replacement_fs.isfile(replacement_path)
replacement_dir = file
replacement_dir_exists = replacement_fs.isdir(replacement_dir)
if len(ja2_images) == 1 and replacement_file_exists:
print("Replacing {0} with {1}".format(file, replacement_path))
replacement_img = Image.open(replacement_fs.open(replacement_path, 'rb'))
ja2_images._palette = replacement_img.palette
ja2_images.images[0]._image = replacement_img
elif len(ja2_images) > 1 and replacement_dir_exists:
for i in range(len(ja2_images)):
replacement_path = replacement_dir + '/{}.gif'.format(i)
print("Replacing {0} with {1}".format(file, replacement_path))
replacement_img = Image.open(replacement_fs.open(replacement_path, 'rb'))
ja2_images._palette = replacement_img.palette
ja2_images.images[i]._image = replacement_img
else:
print("Replacing {0} with nothingness".format(file))
for sub_image in ja2_images.images:
width, height = sub_image.image.size
sub_image._image = Image.new('P', (width, height), color=54)
save_8bit_sti(ja2_images, target)
with open(args.output, 'wb') as target_file:
target_fs.save(target_file)
示例2: export
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def export(self, location, output_directory):
content = self.find(location)
if content.import_path is not None:
output_directory = output_directory + '/' + os.path.dirname(content.import_path)
if not os.path.exists(output_directory):
os.makedirs(output_directory)
disk_fs = OSFS(output_directory)
with disk_fs.open(content.name, 'wb') as asset_file:
asset_file.write(content.data)
示例3: publish
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def publish(self):
super(PyFS, self).publish()
deploy_fs = OSFS(self.site.config.deploy_root_path.path)
for (dirnm, local_filenms) in deploy_fs.walk():
logger.info("Making directory: %s", dirnm)
self.fs.makedir(dirnm, allow_recreate=True)
remote_fileinfos = self.fs.listdirinfo(dirnm, files_only=True)
# Process each local file, to see if it needs updating.
for filenm in local_filenms:
filepath = pathjoin(dirnm, filenm)
# Try to find an existing remote file, to compare metadata.
for (nm, info) in remote_fileinfos:
if nm == filenm:
break
else:
info = {}
# Skip it if the etags match
if self.check_etag and "etag" in info:
with deploy_fs.open(filepath, "rb") as f:
local_etag = self._calculate_etag(f)
if info["etag"] == local_etag:
logger.info("Skipping file [etag]: %s", filepath)
continue
# Skip it if the mtime is more recent remotely.
if self.check_mtime and "modified_time" in info:
local_mtime = deploy_fs.getinfo(filepath)["modified_time"]
if info["modified_time"] > local_mtime:
logger.info("Skipping file [mtime]: %s", filepath)
continue
# Upload it to the remote filesystem.
logger.info("Uploading file: %s", filepath)
with deploy_fs.open(filepath, "rb") as f:
self.fs.setcontents(filepath, f)
# Process each remote file, to see if it needs deleting.
for (filenm, info) in remote_fileinfos:
filepath = pathjoin(dirnm, filenm)
if filenm not in local_filenms:
logger.info("Removing file: %s", filepath)
self.fs.remove(filepath)
示例4: export
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def export(self, location, output_directory):
content = self.find(location)
filename = content.name
if content.import_path is not None:
output_directory = output_directory + '/' + os.path.dirname(content.import_path)
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# Escape invalid char from filename.
export_name = escape_invalid_characters(name=filename, invalid_char_list=['/', '\\'])
disk_fs = OSFS(output_directory)
with disk_fs.open(export_name, 'wb') as asset_file:
asset_file.write(content.data)
示例5: export
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def export(course, export_dir):
"""Export the specified course to course_dir. Creates dir if it doesn't exist.
Overwrites files, does not clean out dir beforehand.
"""
fs = OSFS(export_dir, create=True)
if not fs.isdirempty("."):
print ("WARNING: Directory {dir} not-empty." " May clobber/confuse things".format(dir=export_dir))
try:
xml = course.export_to_xml(fs)
with fs.open("course.xml", mode="w") as f:
f.write(xml)
return True
except:
print "Export failed!"
traceback.print_exc()
return False
示例6: export
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def export(course, export_dir):
"""Export the specified course to course_dir. Creates dir if it doesn't exist.
Overwrites files, does not clean out dir beforehand.
"""
fs = OSFS(export_dir, create=True)
if not fs.isdirempty('.'):
print ('WARNING: Directory {dir} not-empty.'
' May clobber/confuse things'.format(dir=export_dir))
try:
course.runtime.export_fs = fs
root = lxml.etree.Element('root')
course.add_xml_to_node(root)
with fs.open('course.xml', mode='w') as f:
root.write(f)
return True
except:
print 'Export failed!'
traceback.print_exc()
return False
示例7: test_export_course
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def test_export_course(self):
module_store = modulestore('direct')
draft_store = modulestore('draft')
content_store = contentstore()
import_from_xml(module_store, 'common/test/data/', ['full'])
location = CourseDescriptor.id_to_location('edX/full/6.002_Spring_2012')
# get a vertical (and components in it) to put into 'draft'
vertical = module_store.get_item(Location(['i4x', 'edX', 'full',
'vertical', 'vertical_66', None]), depth=1)
draft_store.clone_item(vertical.location, vertical.location)
# We had a bug where orphaned draft nodes caused export to fail. This is here to cover that case.
draft_store.clone_item(vertical.location, Location(['i4x', 'edX', 'full',
'vertical', 'no_references', 'draft']))
for child in vertical.get_children():
draft_store.clone_item(child.location, child.location)
root_dir = path(mkdtemp_clean())
# now create a private vertical
private_vertical = draft_store.clone_item(vertical.location,
Location(['i4x', 'edX', 'full', 'vertical', 'a_private_vertical', None]))
# add private to list of children
sequential = module_store.get_item(Location(['i4x', 'edX', 'full',
'sequential', 'Administrivia_and_Circuit_Elements', None]))
private_location_no_draft = private_vertical.location.replace(revision=None)
module_store.update_children(sequential.location, sequential.children +
[private_location_no_draft.url()])
# read back the sequential, to make sure we have a pointer to
sequential = module_store.get_item(Location(['i4x', 'edX', 'full',
'sequential', 'Administrivia_and_Circuit_Elements', None]))
self.assertIn(private_location_no_draft.url(), sequential.children)
print 'Exporting to tempdir = {0}'.format(root_dir)
# export out to a tempdir
export_to_xml(module_store, content_store, location, root_dir, 'test_export', draft_modulestore=draft_store)
# check for static tabs
self.verify_content_existence(module_store, root_dir, location, 'tabs', 'static_tab', '.html')
# check for custom_tags
self.verify_content_existence(module_store, root_dir, location, 'info', 'course_info', '.html')
# check for custom_tags
self.verify_content_existence(module_store, root_dir, location, 'custom_tags', 'custom_tag_template')
# check for about content
self.verify_content_existence(module_store, root_dir, location, 'about', 'about', '.html')
# check for graiding_policy.json
filesystem = OSFS(root_dir / 'test_export/policies/6.002_Spring_2012')
self.assertTrue(filesystem.exists('grading_policy.json'))
course = module_store.get_item(location)
# compare what's on disk compared to what we have in our course
with filesystem.open('grading_policy.json', 'r') as grading_policy:
on_disk = loads(grading_policy.read())
self.assertEqual(on_disk, course.grading_policy)
#check for policy.json
self.assertTrue(filesystem.exists('policy.json'))
# compare what's on disk to what we have in the course module
with filesystem.open('policy.json', 'r') as course_policy:
on_disk = loads(course_policy.read())
self.assertIn('course/6.002_Spring_2012', on_disk)
self.assertEqual(on_disk['course/6.002_Spring_2012'], own_metadata(course))
# remove old course
delete_course(module_store, content_store, location)
# reimport
import_from_xml(module_store, root_dir, ['test_export'], draft_store=draft_store)
items = module_store.get_items(Location(['i4x', 'edX', 'full', 'vertical', None]))
self.assertGreater(len(items), 0)
for descriptor in items:
# don't try to look at private verticals. Right now we're running
# the service in non-draft aware
if getattr(descriptor, 'is_draft', False):
print "Checking {0}....".format(descriptor.location.url())
resp = self.client.get(reverse('edit_unit', kwargs={'location': descriptor.location.url()}))
self.assertEqual(resp.status_code, 200)
# verify that we have the content in the draft store as well
vertical = draft_store.get_item(Location(['i4x', 'edX', 'full',
'vertical', 'vertical_66', None]), depth=1)
self.assertTrue(getattr(vertical, 'is_draft', False))
for child in vertical.get_children():
self.assertTrue(getattr(child, 'is_draft', False))
#.........这里部分代码省略.........
示例8: cmd_render
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
def cmd_render(self, *params, **options):
icon_sizes = ','.join(str(s) for s in sorted(settings.DESKTOP_FORCE_ICON_SIZES))
num_rendered = 0
from linkstop.threadpool import ThreadPool
thread_pool = ThreadPool(3, 6)
try:
max_renders = int(params[0])
except IndexError:
max_renders = None
qs = FavIcon.objects.filter(rendered=False).order_by('pk')
media_fs = OSFS(settings.MEDIA_ROOT)
media_fs.makedir('favicons', allow_recreate=True)
try:
for favicon in qs:
original_sizes = favicon.get_original_sizes()
if not original_sizes:
continue
remaining_sizes = sorted(set(settings.DESKTOP_FORCE_ICON_SIZES).difference(favicon.get_sizes()))
for size in remaining_sizes:
print "Rendering %ix%i icon" % (size, size)
image_path = os.path.join( settings.MEDIA_ROOT,
url_to_path(favicon.url), 'icon%i.png' % original_sizes[-1] )
output_path = get_size_path(favicon.url, size)
thread_pool.job( render,
(size, size),
image_path,
output_path,
settings.FAVICON_POV_SCENE )
favicon.sizes = icon_sizes
favicon.rendered = True
favicon.save()
#favicon_path = url_to_path(favicon.url)
#favicon_fs = media_fs.makeopendir(favicon_path, recursive=True)
favicon_fs = OSFS(get_icon_directory(favicon.url), create=True)
favicon.export(favicon_fs.open('scan.pik', 'w'))
#pickle_path = favicon_fs.getsyspath('scan.pik')
num_rendered += 1
if max_renders is not None and num_rendered >= max_renders:
break
finally:
thread_pool.flush_quit()
print "%i icon sets rendered" % num_rendered
示例9: Timeline
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
class Timeline(object):
"""A timeline is a sequence of timestamped events."""
def __init__(self, path, name, max_events=None):
self.path = path
self.name = name
self.fs = OSFS(path, create=True)
self.max_events = max_events
def __repr__(self):
return "Timeline({!r}, {!r}, max_events={!r})".format(self.path, self.name, self.max_events)
def new_event(self, event_type, timestamp=None, *args, **kwargs):
"""Create and return an event, to be used as a context manager"""
if self.max_events is not None:
size = len(self.fs.listdir(wildcard="*.json"))
if size >= self.max_events:
raise TimelineFullError("The timeline has reached its maximum size")
if timestamp is None:
timestamp = int(time() * 1000.0)
try:
event_cls = _event_registry[event_type]
except KeyError:
raise UnknownEventError("No event type '{}'".format(event_type))
# Make an event id that we can be confident it's unique
token = str(randint(0, 2 ** 31))
event_id = kwargs.pop('event_id', None) or "{}_{}_{}".format(event_type, timestamp, token)
event = event_cls(self, event_id, timestamp, *args, **kwargs)
log.debug('new event {!r}'.format(event))
return event
def new_photo(self, file, filename=None, ext=None, **kwargs):
"""Create a new photo object"""
event = self.new_event('IMAGE', **kwargs)
if hasattr(file, 'getvalue'):
bytes = file.getvalue()
elif file is not None:
if isinstance(file, text_type):
with open(file, 'rb') as f:
bytes = f.read()
else:
bytes = file.read()
else:
if bytes is None:
raise ValueError("A value for 'file' or 'bytes' is required")
event.attach_bytes(bytes, name='photo', filename=filename, ext=ext)
return event
def get_events(self, sort=True):
"""Get all accumulated events"""
events = []
for event_filename in self.fs.listdir(wildcard="*.json"):
with self.fs.open(event_filename, 'rb') as f:
event = loads(f.read().decode('utf-8'))
events.append(event)
if sort:
# sort by timestamp
events.sort(key=itemgetter('timestamp'))
return events
def clear_all(self):
"""Clear all stored events"""
for filename in self.fs.listdir(wildcard="*.json"):
try:
self.fs.remove(filename)
except FSError:
pass
def clear_events(self, event_ids):
"""Clear any events that have been processed"""
for event_id in event_ids:
filename = "{}.json".format(event_id)
try:
self.fs.remove(filename)
except FSError:
pass
def _write_event(self, event_id, event):
if hasattr(event, 'to_data'):
event = event.to_data()
event['event_id'] = event_id
event_json = dumps(event, indent=4).encode('utf-8')
filename = "{}.json".format(event_id)
with self.fs.open(filename, 'wb') as f:
f.write(event_json)
示例10: OSFS
# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import open [as 别名]
from fs.osfs import OSFS
import Image
img_fs = OSFS(sys.argv[1])
imgs = []
for path in img_fs.listdir(wildcard='*.png'):
img = Image.open(img_fs.getsyspath(path))
size = img.size[0]
if size != 16:
continue
imgs.append((path, img))
sprite = Image.new('RGBA', (16, len(imgs)*16))
imgs.sort(key=lambda i:i[0])
sprite_text_f = img_fs.open('sprites.txt', 'wt')
for i, (path, img) in enumerate(imgs):
y = i*16
sprite.paste(img, (0, y))
sprite_text_f.write( "%i\t%s\n" % (y, path))
sprite.save(img_fs.getsyspath('sprites.png'))
sprite_text_f.close()