• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python fs.Directory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mynt.fs.Directory的典型用法代码示例。如果您正苦于以下问题:Python Directory类的具体用法?Python Directory怎么用?Python Directory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Directory类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _generate

 def _generate(self):
     self._initialize()
     self._parse()
     self._render()
     
     logger.info('>> Generating')
     
     assets_src = Directory(normpath(self.src.path, '_assets'))
     assets_dest = Directory(normpath(self.dest.path, *self.config['assets_url'].split('/')))
     
     if self.dest.exists:
         if self.opts['force']:
             self.dest.empty()
         else:
             self.dest.rm()
     else:
         self.dest.mk()
     
     for page in self.pages:
         page.mk()
     
     assets_src.cp(assets_dest.path)
     
     for pattern in self.config['include']:
         for path in iglob(normpath(self.src.path, pattern)):
             dest = path.replace(self.src.path, self.dest.path)
             
             if op.isdir(path):
                 Directory(path).cp(dest, False)
             elif op.isfile(path):
                 File(path).cp(dest)
开发者ID:Anomareh,项目名称:mynt,代码行数:31,代码来源:core.py


示例2: watch

    def watch(self):
        self.src = Directory(self.opts['src'])
        self.dest = Directory(self.opts['dest'])

        if not self.src.exists:
            raise OptionException('Source must exist.')
        elif self.src == self.dest:
            raise OptionException('Source and destination must differ.')
        elif self.dest.exists and not self.opts['force']:
            raise OptionException('Destination already exists.',
                'the -f flag must be passed to force watching by emptying the destination every time a change is made')

        logger.info('>> Watching')
        logger.info('Press ctrl+c to stop.')

        self.observer = Observer()

        self.observer.schedule(EventHandler(self.src.path, self._regenerate), self.src.path, True)
        self.observer.start()

        try:
            while True:
                sleep(1)
        except KeyboardInterrupt:
            self.observer.stop()

            print('')

        self.observer.join()
开发者ID:shamansir,项目名称:mynt,代码行数:29,代码来源:core.py


示例3: init

    def init(self):
        Timer.start()

        self.src = Directory(self._get_theme(self.opts['theme']))
        self.dest = Directory(self.opts['dest'])

        if not self.src.exists:
            raise OptionException('Theme not found.')
        elif self.dest.exists and not self.opts['force']:
            raise OptionException('Destination already exists.',
                'the -f flag must be passed to force initialization by deleting the destination')

        logger.info('>> Initializing')

        if self.opts['bare']:
            self.dest.rm()

            for d in ('_assets/css', '_assets/images', '_assets/js', '_templates', '_posts'):
                Directory(normpath(self.dest.path, d)).mk()

            File(normpath(self.dest.path, 'config.yml')).mk()
        else:
            self.src.cp(self.dest.path, False)

        logger.info('Completed in %.3fs', Timer.stop())
开发者ID:shamansir,项目名称:mynt,代码行数:25,代码来源:core.py


示例4: generate

 def generate(self):
     self.src = Directory(self.opts['src'])
     self.dest = Directory(self.opts['dest'])
     
     if not self.src.exists:
         raise OptionException('Source must exist.')
     elif self.src == self.dest:
         raise OptionException('Source and destination must differ.')
     elif self.dest.exists and not (self.opts['force'] or self.opts['clean']):
         raise OptionException('Destination already exists.', 'the -c or -f flag must be passed to force generation by deleting or emptying the destination')
     
     self._generate()
开发者ID:geerk,项目名称:mynt,代码行数:12,代码来源:core.py


示例5: _generate

 def _generate(self):
     logger.debug('>> Initializing\n..  src:  %s\n..  dest: %s', self.src.path, self.dest.path)
     
     self._update_config()
     
     if self.config['locale']:
         try:
             locale.setlocale(locale.LC_ALL, (self.config['locale'], 'utf-8'))
         except locale.Error:
             raise ConfigException('Locale not available.', 'run `locale -a` to see available locales')
     
     self.renderer.register({'site': self.config})
     
     self._render()
     
     logger.info('>> Generating')
     
     assets_src = Directory(normpath(self.src.path, '_assets'))
     assets_dest = Directory(normpath(self.dest.path, *self.config['assets_url'].split('/')))
     
     if self.dest.exists:
         if self.opts['force']:
             self.dest.empty()
         else:
             self.dest.rm()
     else:
         self.dest.mk()
     
     for page in self.pages:
         page.mk()
     
     assets_src.cp(assets_dest.path)
     
     for pattern in self.config['include']:
         for path in iglob(normpath(self.src.path, pattern)):
             dest = path.replace(self.src.path, self.dest.path)
             
             if op.isdir(path):
                 Directory(path).cp(dest, False)
             elif op.isfile(path):
                 File(path).cp(dest)
     
     logger.info('Completed in %.3fs', time() - self._start)
开发者ID:geerk,项目名称:mynt,代码行数:43,代码来源:core.py


示例6: generate

 def generate(self):
     self.src = Directory(self.opts['src'])
     self.dest = Directory(self.opts['dest'])
     
     if not self.src.exists:
         raise OptionException('Source must exist.')
     elif self.src == self.dest:
         raise OptionException('Source and destination must differ.')
     elif self.src.path in ('/', '//') or self.dest.path in ('/', '//'):
         raise OptionException('Root is not a valid source or destination.')
     elif self.dest.exists and not (self.opts['force'] or self.opts['clean']):
         raise OptionException('Destination already exists.', 'the -c or -f option must be used to force generation')
     
     self._generate()
开发者ID:jag3773,项目名称:mynt,代码行数:14,代码来源:core.py


示例7: init

 def init(self):
     self.src = Directory(self._get_theme(self.opts['theme']))
     self.dest = Directory(self.opts['dest'])
     
     if not self.src.exists:
         raise OptionException('Theme not found.')
     elif self.dest.exists and not self.opts['force']:
         raise OptionException('Destination already exists.', 'the -f option must be used to force initialization by deleting the destination')
     
     logger.info('>> Initializing')
     
     if self.opts['bare']:
         for d in ['_assets/css', '_assets/images', '_assets/js', '_templates', '_posts']:
             Directory(normpath(self.dest.path, d)).mk()
         
         File(normpath(self.dest.path, 'config.yml')).mk()
     else:
         self.src.cp(self.dest.path)
     
     logger.info('Completed in {0:.3f}s'.format(time() - self._start))
开发者ID:jag3773,项目名称:mynt,代码行数:20,代码来源:core.py


示例8: serve

    def serve(self):
        self.src = Directory(self.opts['src'])
        base_url = Url.join(self.opts['base_url'], '')

        if not self.src.exists:
            raise OptionException('Source must exist.')

        logger.info('>> Serving at 127.0.0.1:%s', self.opts['port'])
        logger.info('Press ctrl+c to stop.')

        cwd = getcwd()
        self.server = Server(('', self.opts['port']), base_url, RequestHandler)

        chdir(self.src.path)

        try:
            self.server.serve_forever()
        except KeyboardInterrupt:
            self.server.shutdown()
            chdir(cwd)

            print('')
开发者ID:shamansir,项目名称:mynt,代码行数:22,代码来源:core.py


示例9: __init__

 def __init__(self, args = None):
     self._start = time()
     
     self.opts = self._get_opts(args)
     
     self.src = Directory(self.opts['src'])
     self.dest = Directory(self.opts['dest'])
     
     logger.setLevel(getattr(logging, self.opts['level'], logging.INFO))
     logger.debug('>> Initializing\n..  src:  {0}\n..  dest: {1}'.format(self.src, self.dest))
     
     if self.src == self.dest:
         raise OptionException('Source and destination must differ.')
     elif self.src.path in ('/', '//') or self.dest.path in ('/', '//'):
         raise OptionException('Root is not a valid source or destination.')
     
     logger.debug('>> Searching for config')
     
     for ext in ('.yml', '.yaml'):
         f = File(normpath(self.src.path, 'config' + ext))
         
         if f.exists:
             logger.debug('..  found: {0}'.format(f.path))
             
             try:
                 self.config.update(Config(f.content))
             except ConfigException as e:
                 raise ConfigException(e.message, 'src: {0}'.format(f.path))
             
             break
     else:
         logger.debug('..  no config file found')
     
     for opt in ('base_url',):
         if opt in self.opts:
             self.config[opt] = self.opts[opt]
     
     self.renderer.register({'site': self.config})
开发者ID:dogonwheels,项目名称:mynt,代码行数:38,代码来源:core.py


示例10: Mynt


#.........这里部分代码省略.........
                locale.setlocale(locale.LC_ALL, (self.config['locale'], 'utf-8'))
            except locale.Error:
                raise ConfigException('Locale not available.',
                    'run `locale -a` to see available locales')

        self.writer.register({'site': self.config})

    def _parse(self):
        logger.info('>> Parsing')

        self.posts, self.containers, self.pages = self.reader.parse()

        self.data['posts'] = self.posts.data
        self.data['containers'] = {}

        for name, container in self.containers.iteritems():
            self.data['containers'][name] = container.data

    def _render(self):
        logger.info('>> Rendering')

        self.writer.register(self.data)

        for i, page in enumerate(self.pages):
            self.pages[i] = self.writer.render(*page)

    def _generate(self):
        self._initialize()
        self._parse()
        self._render()

        logger.info('>> Generating')

        assets_src = Directory(normpath(self.src.path, '_assets'))
        assets_dest = Directory(normpath(self.dest.path, *self.config['assets_url'].split('/')))

        figures_src = Directory(normpath(self.src.path, '_figures'))
        figures_dest = Directory(normpath(self.dest.path, *self.config['figures_url'].split('/')))

        if self.dest.exists:
            if self.opts['force']:
                self.dest.empty()
            else:
                self.dest.rm()
        else:
            self.dest.mk()

        for page in self.pages:
            page.mk()

        assets_src.cp(assets_dest.path)
        figures_src.cp(figures_dest.path)

        for pattern in self.config['include']:
            for path in iglob(normpath(self.src.path, pattern)):
                dest = path.replace(self.src.path, self.dest.path)

                if op.isdir(path):
                    Directory(path).cp(dest, False)
                elif op.isfile(path):
                    File(path).cp(dest)

    def _regenerate(self):
        self._reader = None
        self._writer = None
开发者ID:shamansir,项目名称:mynt,代码行数:66,代码来源:core.py


示例11: Mynt


#.........这里部分代码省略.........
            
            if f.exists:
                logger.debug('..  found: %s', f.path)
                
                try:
                    self.config.update(Config(f.content))
                except ConfigException as e:
                    raise ConfigException(e.message, 'src: {0}'.format(f.path))
                
                self.config['locale'] = self.opts.get('locale', self.config['locale'])
                
                self.config['assets_url'] = absurl(self.config['assets_url'], '')
                self.config['base_url'] = absurl(self.opts.get('base_url', self.config['base_url']), '')
                
                for setting in ('archives_url', 'posts_url', 'tags_url'):
                    self.config[setting] = absurl(self.config[setting])
                
                for setting in ('archives_url', 'assets_url', 'base_url', 'posts_url', 'tags_url'):
                    if re.search(r'(?:^\.{2}/|/\.{2}$|/\.{2}/)', self.config[setting]):
                        raise ConfigException('Invalid config setting.', 'setting: {0}'.format(setting), 'path traversal is not allowed')
                
                for pattern in self.config['include']:
                    if op.commonprefix((self.src.path, normpath(self.src.path, pattern))) != self.src.path:
                        raise ConfigException('Invalid include path.', 'path: {0}'.format(pattern), 'path traversal is not allowed')
                
                break
        else:
            logger.debug('..  no config file found')
    
    
    def _parse(self):
        logger.info('>> Parsing')
        
        path = Directory(normpath(self.src.path, '_posts'))
        
        logger.debug('..  src: %s', path)
        
        for f in path:
            post = Post(f)
            
            content = self.parser.parse(self.renderer.from_string(post.bodymatter, post.frontmatter))
            excerpt = re.search(r'\A.*?(?:<p>(.+?)</p>)?', content, re.M | re.S).group(1)
            
            try:
                data = {
                    'content': content,
                    'date': post.date.strftime(self.config['date_format']).decode('utf-8'),
                    'excerpt': excerpt,
                    'tags': [],
                    'timestamp': timegm(post.date.utctimetuple()),
                    'url': self._get_post_url(post.date, post.slug)
                }
            except PageException:
                raise PageException('Invalid post slug.', 'src: {0}'.format(post.path))
            
            data.update(post.frontmatter)
            data['tags'].sort(key = unicode.lower)
            
            self.posts.append(data)
            
            for tag in data['tags']:
                if tag not in self.tags:
                    self.tags[tag] = []
                
                self.tags[tag].append(data)
    
开发者ID:geerk,项目名称:mynt,代码行数:66,代码来源:core.py


示例12: Mynt

class Mynt(object):
    config = {
        'archive_layout': None,
        'archives_url': '/',
        'assets_url': '/assets',
        'base_url': '/',
        'date_format': '%A, %B %d, %Y',
        'markup': 'markdown',
        'parser': 'misaka',
        'posts_url': '/<year>/<month>/<day>/<title>/',
        'pygmentize': True,
        'renderer': 'jinja',
        'tag_layout': None,
        'tags_url': '/',
        'version': __version__
    }
    
    _parser = None
    _renderer = None
    
    archives = OrderedDict()
    pages = []
    posts = []
    tags = OrderedDict()
    
    
    def __init__(self, args = None):
        self._start = time()
        
        self.opts = self._get_opts(args)
        
        self.src = Directory(self.opts['src'])
        self.dest = Directory(self.opts['dest'])
        
        logger.setLevel(getattr(logging, self.opts['level'], logging.INFO))
        logger.debug('>> Initializing\n..  src:  {0}\n..  dest: {1}'.format(self.src, self.dest))
        
        if self.src == self.dest:
            raise OptionException('Source and destination must differ.')
        elif self.src.path in ('/', '//') or self.dest.path in ('/', '//'):
            raise OptionException('Root is not a valid source or destination.')
        
        logger.debug('>> Searching for config')
        
        for ext in ('.yml', '.yaml'):
            f = File(normpath(self.src.path, 'config' + ext))
            
            if f.exists:
                logger.debug('..  found: {0}'.format(f.path))
                
                try:
                    self.config.update(Config(f.content))
                except ConfigException as e:
                    raise ConfigException(e.message, 'src: {0}'.format(f.path))
                
                break
        else:
            logger.debug('..  no config file found')
        
        for opt in ('base_url',):
            if opt in self.opts:
                self.config[opt] = self.opts[opt]
        
        self.renderer.register({'site': self.config})
    
    
    def _get_archives_url(self, year):
        format = self._get_url_format(self.config['tags_url'].endswith('/'))
        
        return format.format(self.config['archives_url'], year)
    
    def _get_opts(self, args):
        opts = {}
        
        parser = ArgumentParser(description = 'A static blog generator.')
        
        parser.add_argument('src', nargs = '?', default = '.', metavar = 'source', help = 'The location %(prog)s looks for source files.')
        parser.add_argument('dest', metavar = 'destination', help = 'The location %(prog)s outputs to.')
        
        level = parser.add_mutually_exclusive_group()
        
        level.add_argument('-l', '--level', default = b'INFO', type = str.upper, choices = ['DEBUG', 'INFO', 'WARNING', 'ERROR'], help = 'Sets %(prog)s\'s log level.')
        level.add_argument('-q', '--quiet', action = 'store_const', const = 'ERROR', dest = 'level', help = 'Sets %(prog)s\'s log level to ERROR.')
        level.add_argument('-v', '--verbose', action = 'store_const', const = 'DEBUG', dest = 'level', help = 'Sets %(prog)s\'s log level to DEBUG.')
        
        parser.add_argument('--base-url', help = 'Sets the site\'s base URL.')
        parser.add_argument('-f', '--force', action = 'store_true', help = 'Forces generation deleting the destination if it already exists.')
        
        parser.add_argument('-V', '--version', action = 'version', version = '%(prog)s v{0}'.format(__version__), help = 'Prints %(prog)s\'s version and exits.')
        
        for option, value in vars(parser.parse_args(args)).iteritems():
            if value is not None:
                if isinstance(option, str):
                    option = option.decode('utf-8')
                
                if isinstance(value, str):
                    value = value.decode('utf-8')
                
                opts[option] = value
        
#.........这里部分代码省略.........
开发者ID:dogonwheels,项目名称:mynt,代码行数:101,代码来源:core.py


示例13: Mynt


#.........这里部分代码省略.........
        self.config = deepcopy(self.defaults)

        logger.debug('>> Searching for config')

        for ext in ('.yml', '.yaml'):
            f = File(normpath(self.src.path, 'config' + ext))

            if f.exists:
                logger.debug('..  found: {0}'.format(f.path))

                try:
                    self.config.update(Config(f.content))
                except ConfigException as e:
                    raise ConfigException(e.message, 'src: {0}'.format(f.path))

                break
        else:
            logger.debug('..  no config file found')

        # suport for the time_locale
        if self.config['time_locale']:
            # ascii-encoding is fallback for: http://bugs.python.org/issue3067
            time_locale = self.config['time_locale'].encode('ascii')
            logger.debug('.. chaning time locale to ' + time_locale)
            try:
                locale.setlocale(locale.LC_TIME, (time_locale, b'utf-8'))
            except ValueError:
                logger.error('Wrong time locale format: {0} ({1})'.format(time_locale, type(time_locale)))


    def _parse(self):
        logger.info('>> Parsing')

        path = Directory(normpath(self.src.path, '_posts'))

        logger.debug('..  src: {0}'.format(path))

        for f in path:
            post = Post(f)

            postdate = post.date.strftime(self.config['date_format']).decode('utf-8')

            logger.debug('.. .. postdate: {0}'.format(postdate))

            content = self.parser.parse(self.renderer.from_string(post.bodymatter, post.frontmatter))
            excerpt = re.search(r'\A.*?(?:<p>(.+?)</p>)?', content, re.M | re.S).group(1)

            if self.config['check_more']:
                # check for the more tag if set, then check the posts for it
                # because if set in config, use it for the posts
                # do nothing if not found
                logger.debug('.. checking the <!--more--> tag')
                more_excerpt = re.search(r'(\A.*?)(?:<!--more-->).*', content, re.M | re.S)
                if more_excerpt != None:
                    excerpt = more_excerpt.group(1)

            data = {
                'content': content,
                'date': post.date.strftime(self.config['date_format']).decode('utf-8'),
                'excerpt': excerpt,
                'tags': [],
                'timestamp': timegm(post.date.utctimetuple()),
                'url': self._get_post_url(post.date, post.slug)
            }

            data.update(post.frontmatter)
开发者ID:cblte,项目名称:mynt,代码行数:67,代码来源:core.py



注:本文中的mynt.fs.Directory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.normpath函数代码示例发布时间:2022-05-27
下一篇:
Python mymysql.connectDB函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap