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

Python unipath.Path类代码示例

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

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



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

示例1: enviar_email_con_cupon

def enviar_email_con_cupon(modeladmin, request, queryset):
    leads_incorrectos = 0
    leads_correctos = 0
    for lead in queryset:
        if lead.enviado_en_csv is True and lead.enviado_cupon is False and lead.colectivo_validado is True:
            for fichero in os.listdir(settings.COUPONS_ROOT):
                if fnmatch.fnmatch(fichero, str(lead.id)+'_*.pdf'):
                    cupon_fichero = Path(settings.COUPONS_ROOT, fichero)
                    if cupon_fichero.exists():
                        codigo = fichero.split("_")[1].split(".")[0]
                        url_cupon = settings.BASE_URL+'/static/coupons/'+fichero
                        mail = EmailMultiAlternatives(
                            subject="Mi cupón de 10€ de Juguetes Blancos",
                            body='Descarga tu cupon aqui: '+url_cupon+' </p>',
                            from_email="Rocio, JueguetesBlancos <[email protected]>",
                            to=[lead.email]
                        )
                        mail.attach_alternative(render_to_string('leads/email_cupon.html', {'lead': lead, 'url_cupon': url_cupon}), "text/html")
                        mail.send()
                        lead.enviado_cupon = True
                        lead.codigo_cupon = codigo
                        lead.save()
                        leads_correctos = leads_correctos+1
        else:
            leads_incorrectos = leads_incorrectos+1
    messages.success(request, str(leads_correctos)+' Email/s enviado Correctamente')
    messages.error(request, str(leads_incorrectos)+' Leads no cumplian las condiciones.')
开发者ID:jelukas,项目名称:tarifasb2bpromo,代码行数:27,代码来源:admin.py


示例2: test_dump2py

 def test_dump2py(self):
     for prj in ["lino_book/projects/belref"]:
         p = Path(prj)
         tmp = p.child('tmp').absolute()
         tmp.rmtree()
         self.run_django_admin_command_cd(p, 'dump2py', tmp)
         self.assertEqual(tmp.child('restore.py').exists(), True)
开发者ID:khchine5,项目名称:book,代码行数:7,代码来源:test_misc.py


示例3: SymlinkItem

class SymlinkItem(BaseItem):
    src = None
    destination = None

    def __init__(self, src, destination):
        self.src = Path(src)
        self.destination = Path(destination)

    def run(self, context):
        if not self.src.isabsolute():
            self.src = Path(Path(context['target_dir']), self.src)

        if self.destination.isabsolute():
            destination = Path(context['package_root'], strip_root(self.destination))
        else:
            destination = Path(context['package_project_dir'], self.destination)

        parent_dir = destination.parent
        if not parent_dir.exists():
            parent_dir.mkdir(parents=True, mode=0777)

        command = 'ln -s %(src)s %(destination)s' % {
            'src': self.src,
            'destination': destination
        }
        fabric.api.local(command, capture=True)
开发者ID:phonkee,项目名称:easyfab,代码行数:26,代码来源:items.py


示例4: __init__

    def __init__(self, release_search_dir, tmp_dir, unpack_dir,
                 no_remove=False):
        self.release_search_dir = Path(release_search_dir)
        self.release_search_dir_abs = self.release_search_dir.absolute()
        self.tmp_dir = Path(tmp_dir)
        self.unpack_dir = Path(unpack_dir)
        self.no_remove = no_remove

        if not self.release_search_dir_abs.exists():
            raise ReleaseUnpackerError(
                'Release search dir {} doesn\'t exist'.format(
                    self.release_search_dir))
        elif not self.release_search_dir_abs.isdir():
            raise ReleaseUnpackerError(
                'Release search dir {} is not a dir'.format(
                    self.release_search_dir))
        elif not self.tmp_dir.exists():
            raise ReleaseUnpackerError(
                'Tmp dir {} doesn\'t exist'.format(self.tmp_dir))
        elif not self.tmp_dir.isdir():
            raise ReleaseUnpackerError(
                'Tmp dir {} is not a dir'.format(
                    self.tmp_dir))
        elif not self.unpack_dir.exists():
            raise ReleaseUnpackerError(
                'Unpack dir {} doesn\'t exist'.format(self.unpack_dir))
        elif not self.unpack_dir.isdir():
            raise ReleaseUnpackerError(
                'Unpack dir {} is not a dir'.format(
                    self.unpack_dir))
开发者ID:dnxxx,项目名称:releaseunpacker,代码行数:30,代码来源:releaseunpacker.py


示例5: process_directory

def process_directory(directory, context, variable_start_string='{<',
                      variable_end_string='>}', extensions=None,
                      filter=FILES_NO_LINKS):
    directory = Path(directory)

    for f in directory.walk(filter=filter):
        if extensions:
            if f.ext not in extensions:
                continue

        components = f.components()
        td, tf = Path(*components[:-1]), components[-1]

        jinja_env = Environment(loader=FileSystemLoader(str(td)),
                                variable_start_string=variable_start_string,
                                variable_end_string=variable_end_string,
                                block_start_string='{<%',
                                block_end_string='%>}',
                                comment_start_string='{<#',
                                comment_end_string='#>}',
                                )
        try:
            rendered = jinja_env.get_template(str(tf)).render(**context)
        except Exception, e:
            print "Cannot process file %s on line %s" % (
                e.filename,
                e.lineno
            )
            continue
        f.write_file(rendered.encode('utf-8'))
开发者ID:phonkee,项目名称:easyfab,代码行数:30,代码来源:utils.py


示例6: release

def release():
    """Assemble a release dist package."""
    # create the dist directory 
    with quiet():
        local('rm -rf {}'.format(env.paths['dist']))
        local('mkdir -p {}'.format(env.paths['dist']))
        # find compiled packages
        for (dirpath, dirnames, filenames) in os.walk(env.paths['compiled']):
            files = []
            filename = []
            for path in glob.glob(Path(dirpath).child('*.u')):
                path = Path(path)
                files.append(path)
                # filename has not yet been assembled
                if not filename:
                    # get path of a compile package relative to the directory
                    relpath = Path(os.path.relpath(path, start=env.paths['compiled']))
                    if relpath:
                        # first two components of the assembled dist package name
                        # are the original swat package name and its version..
                        filename = [env.paths['here'].name, env.dist['version']]
                        for component in relpath.components()[1:-1]:
                            # also include names of directories the components
                            # of the relative path
                            filename.append(component.lower())
                        filename.extend(['tar', 'gz'])
            if not files:
                continue
            # tar the following files
            files.extend(env.dist['extra'])
            with lcd(env.paths['dist']):
                local(r'tar -czf "{}" {} '.format(
                    '.'.join(filename),
                    ' '.join(['-C "{0.parent}" "{0.name}"'.format(f) for f in files])
                ))
开发者ID:Miras4207,项目名称:swat-julia,代码行数:35,代码来源:dist.py


示例7: __init__

 def __init__(self, deployment, project_dir, deployment_dir):
     self.deployment = deployment
     self.project_dir = Path(project_dir)
     self.deployment_dir = Path(deployment_dir)
     self.packages_dir = self.deployment_dir.child(".packages")
     self.target_dir = Path(self.target_dir)
     self.deployment_files_dir = deployment_dir.child(deployment)
开发者ID:phonkee,项目名称:easyfab,代码行数:7,代码来源:base.py


示例8: activate_env

def activate_env():
    """ Activates the virtual environment for this project."""

    error_msg = None

    try:
        virtualenv_dir = Path(os.environ['WORKON_HOME'])
    except KeyError:
        error_msg = "Error: 'WORKON_HOME' is not set."

    if error_msg:
        color_init()
        sys.stderr.write(Fore.RED + Style.BRIGHT + error_msg + "\n")
        sys.exit(1)

    filepath = Path(__file__).absolute()
    site_dir = filepath.ancestor(4).components()[-1]
    repo_dir = filepath.ancestor(3).components()[-1]

    # Add the app's directory to the PYTHONPATH
    sys.path.append(filepath.ancestor(2))
    sys.path.append(filepath.ancestor(1))

    # Set manually in environment
    #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.production'

    if os.environ['DJANGO_SETTINGS_MODULE'] == 'settings.production':
        bin_parent = site_dir
    else:
        bin_parent = repo_dir

    # Activate the virtual env
    activate_env = virtualenv_dir.child(bin_parent, "bin", "activate_this.py")
    execfile(activate_env, dict(__file__=activate_env))
开发者ID:copperwall,项目名称:SchedulerTool,代码行数:34,代码来源:manage.py


示例9: environment

def environment(**options):
    queryfinder = QueryFinder()

    searchpath =[]
    staticdirs = []

    sites = settings.SHEER_SITES
    for site in sites:
        site_path = Path(site)
        searchpath.append(site_path)
        searchpath.append(site_path.child('_includes'))
        searchpath.append(site_path.child('_layouts'))
        staticdirs.append(site_path.child('static'))

    options['loader'].searchpath += searchpath
    settings.STATICFILES_DIRS = staticdirs

    env = SheerlikeEnvironment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url_for':url_for,
        'url': reverse,
        'queries': queryfinder,
        'more_like_this': more_like_this,
        'get_document': get_document,
        'selected_filters_for_field': selected_filters_for_field,
        'is_filter_selected': is_filter_selected,
    })
    env.filters.update({
        'date':date_filter
    })
    return env
开发者ID:kave,项目名称:django-sheerlike,代码行数:32,代码来源:__init__.py


示例10: get_closest_uid

def get_closest_uid(path):
	path = Path(path)
	while not path.isdir():
		path = path.ancestor(1)
		if path == '/':
			return False
	return path.stat().st_uid
开发者ID:ball6847,项目名称:docker-django-gitlab-deploy,代码行数:7,代码来源:utils.py


示例11: superuser

def superuser(pubkey=None, username=None):
    """
    fab env superuser
    """
    env.user = 'root'

    keyfile = Path(pubkey or Path('~', '.ssh', 'id_rsa.pub')).expand()

    if not keyfile.exists():
        abort('Public key file does not exist: %s' % keyfile)

    username = username or prompt('Username: ')
    password = getpass('Password: ')
    password = local('perl -e \'print crypt(\"%s\", \"password\")\'' % (password),
                     capture=True)

    with open(keyfile, 'r') as f:
        pubkey = f.read(65535)

    commands = (
        'useradd -m -s /bin/bash -p {password} {username}',
        'mkdir ~{username}/.ssh -m 700',
        'echo "{pubkey}" >> ~{username}/.ssh/authorized_keys',
        'chmod 644 ~{username}/.ssh/authorized_keys',
        'chown -R {username}:{username} ~{username}/.ssh',
        'usermod -a -G sudo {username}',
    )

    for command in commands:
        run(command.format(**locals()))
开发者ID:loogica,项目名称:envkit,代码行数:30,代码来源:setup.py


示例12: set_up_and_import_file

    def set_up_and_import_file(self):
        temp_dir = Path(tempfile.mkdtemp())
        temp_file = Path(temp_dir, 'test.csv')
        with open(temp_file, 'a') as f:
            header = ''
            header_fields = [
                'route',
                'account_number',
                'house_number',
                'pre_direction',
                'street',
                'street_type',
                'post_direction',
                'unit',
                'city_state_zip'
            ]
            
            for x, field in enumerate(header_fields):
                if x + 1 == len(header_fields):
                    header = header + field + '\n'
                else:
                    header = header + field + ','

            f.write(header)
            f.write('123,123,123,S,TEST,RD,S,#5B,"TEST, FL 32174"')

        mommy.make(
            'route_update.Directional', direction='South', abbreviation='S'
        )
        mommy.make('route_update.StreetType', name='Road', abbreviation='RD')
        mommy.make('route_update.State', name='Florida', abbreviation='FL')

        Location.create_active_locations_from_file(temp_file)

        temp_dir.rmtree()
开发者ID:cfc603,项目名称:publication_delivery,代码行数:35,代码来源:test_models.py


示例13: setup_babel_userdocs

def setup_babel_userdocs(babelcmd):
    """Create userdocs .po files if necessary."""
    userdocs = env.root_dir.child('userdocs')
    if not userdocs.isdir():
        return
    locale_dir = userdocs.child('translations')
    for domain in locale_dir.listdir('*.pot', names_only=True):
        domain = domain[:-4]
        for loc in env.languages:
            if loc != env.languages[0]:
                po_file = Path(locale_dir, loc, 'LC_MESSAGES', '%s.po' %
                               domain)
                mo_file = Path(locale_dir, loc, 'LC_MESSAGES', '%s.mo' %
                               domain)
                pot_file = Path(locale_dir, '%s.pot' % domain)
                if babelcmd == 'init_catalog' and po_file.exists():
                    print("Skip %s because file exists." % po_file)
                #~ elif babelcmd == 'compile_catalog' and not mo_file.needs_update(po_file):
                    #~ print "Skip %s because newer than .po" % mo_file
                else:
                    args = ["python", "setup.py"]
                    args += [babelcmd]
                    args += ["-l", loc]
                    args += ["--domain", domain]
                    args += ["-d", locale_dir]
                    #~ args += [ "-o" , po_file ]
                    #~ if babelcmd == 'init_catalog':
                    if babelcmd == 'compile_catalog':
                        args += ["-i", po_file]
                    else:
                        args += ["-i", pot_file]
                    cmd = ' '.join(args)
                    #~ must_confirm(cmd)
                    local(cmd)
开发者ID:khchine5,项目名称:atelier,代码行数:34,代码来源:fablib.py


示例14: load_inv_namespace

def load_inv_namespace(root_dir):
    """
    Execute the :xfile:`tasks.py` file of this project and return its
    `ns`.
    """
    # self._tasks_loaded = True
    
    tasks_file = root_dir.child('tasks.py')
    if not tasks_file.exists():
        return None
        # raise Exception("No tasks.py file in {}".format(root_dir))
        # return

    # print("20180428 load tasks.py from {}".format(root_dir))
    # http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
    # http://stackoverflow.com/questions/19009932/import-arbitrary-python-source-file-python-3-3
    # fqname = 'atelier.prj_%s' % self.index
    cwd = Path().resolve()
    root_dir.chdir()
    m = dict()
    m["__file__"] = str(tasks_file)
    with open(tasks_file) as f:
        exec(f.read(), m)
    cwd.chdir()
    return m['ns']
开发者ID:lino-framework,项目名称:atelier,代码行数:25,代码来源:projects.py


示例15: run

    def run(self, context):
        if not self.directory_name.isabsolute():
            directory = Path(Path(context['package_project_dir']), self.directory_name)
        else:
            directory = Path(context['package_root'], Path(strip_root(self.directory_name)))

        directory.mkdir(parents=True, mode=self.mode)
开发者ID:phonkee,项目名称:easyfab,代码行数:7,代码来源:items.py


示例16: CopyItem

class CopyItem(BaseItem):
    src = None
    destination = None
    only_content = None
    recursive = None

    def __init__(self, src, destination, only_content=False, recursive=False, follow_symlinks=True):
        self.follow_symlinks = follow_symlinks
        self.src = Path(src)
        self.destination = Path(destination)
        self.only_content = only_content
        self.recursive = recursive

    def run(self, context):
        if not self.src.isabsolute():
            self.src = Path(Path(context['project_dir']), self.src)
        if not self.destination.isabsolute():
            self.destination = Path(Path(context['package_project_dir']), self.destination)

        switches = []

        if self.recursive:
            switches.append("-R")

        if self.follow_symlinks:
            switches.append("-L")

        command = 'cp %(switches)s %(src)s %(destination)s' % {
            'switches': ' '.join(switches),
            'src': self.src,
            'destination': self.destination,
        }

        fabric.api.local(command, capture=True)
开发者ID:phonkee,项目名称:easyfab,代码行数:34,代码来源:items.py


示例17: boostrap_nltk_data

def boostrap_nltk_data():
    nltk.data.path.append('./data/')
    nltkdata_exists = Path('./data/tokenizers/punkt/english.pickle')

    if not nltkdata_exists.exists():
        logging.info("Downloading NLTK Data")
        nltk.download('punkt', './data')
开发者ID:jimmytheleaf,项目名称:botutils,代码行数:7,代码来源:ai.py


示例18: delete_file

 def delete_file(self, name):
     """Delete a specific file"""
     if self.ftp:
         self.ftp.delete(name)
     else:
         path = Path(self.path).child(name)
         path.remove()
开发者ID:YukSeungChan,项目名称:alchemydumps,代码行数:7,代码来源:backup.py


示例19: download_qualities

def download_qualities(force=False, i_have_enough_space=False, keep=False):
    url = 'https://ndownloader.figshare.com/files/6059502'
    bz2 = Path(DATA_DIR, 'article_qualities.tsv.bz2')
    tsv = Path(DATA_DIR, 'article_qualities.tsv')

    # Try to prevent accidentally downloading too big a file.
    if not i_have_enough_space:
        try:
            gb_available = int(run("df -g . | awk '/\//{ print $4 }'").stdout)
            if gb_available < 100:
                raise NotEnoughGBAvailable
        except:
            raise NotEnoughGBAvailable
        else:
            logger.info('Rest easy, you have enough space.')
    else:
        logger.info('Skipping space check. Good luck soldier!')

    if SQLITE_PATH.exists() and not force:
        raise DBAlreadyExists

    logger.info('Downloading and decompressing.')
    run('wget {url} > {bz2} && bunzip2 {bz2}'.format(url=url, bz2=bz2))

    logger.info('Importing into sqlite.')
    conn = connect_to_sqlite_db()
    for chunk in pandas.read_table(tsv, chunksize=100000):
        chunk.to_sql('qualities', conn, if_exists='append', index=False)
    conn.close()

    if not keep:
        tsv.remove()
开发者ID:evoapps,项目名称:evotrees,代码行数:32,代码来源:import_qualities.py


示例20: add_deployment

def add_deployment(directory, name, templates_dir='templates', deployment_dir='deployment', mode=0777):
    """ Adds new deployment if not exists
    """
    context = {
        'datetime': datetime.datetime.now(),
        'name': name,
        'project_name': get_project_name(directory)
    }

    dd, df = get_deployment_info(directory, name)

    if df.exists():
        raise ExistingDeploymentError()

    # create deployments directory
    df.parent.mkdir(parents=True, mode=mode)

    # write deployment file
    df.write_file(
        get_rendered_template('deployment.py', context)
    )
    top_td = Path(__file__).parent.child(templates_dir)
    td = top_td.child(deployment_dir)
    for tf in td.walk():
        if tf.isdir():
            continue
        partitioned = tf.partition(td)
        target = Path(dd, Path(partitioned[2][1:]))
        target_dir = target.parent
        if not target_dir.exists():
            target_dir.mkdir(parents=True, mode=mode)
        tmp = tf.partition(top_td)[2][1:]
        rendered = get_rendered_template(tmp, context)
        target.write_file(rendered)
开发者ID:phonkee,项目名称:easyfab,代码行数:34,代码来源:commands.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python unique.filepath函数代码示例发布时间:2022-05-27
下一篇:
Python unipath.FSPath类代码示例发布时间: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