当前位置: 首页>>代码示例>>Python>>正文


Python Path.read_file方法代码示例

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


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

示例1: run

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
    def run(self, username=None, pubkey=None, as_root=False, with_password=True):
        if as_root:
            remote_user = 'root'
            execute = run
        else:
            remote_user = env.local_user
            execute = sudo

        with settings(user=remote_user):
            keyfile = Path(pubkey or Path('~', '.ssh', 'id_rsa.pub')).expand()

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

            pubkey = keyfile.read_file().strip()

            username = username or prompt('Username: ')

            if with_password:
                password = getpass("%s's password: " % username)

                with hide('running', 'stdout', 'stderr'):
                    password = local('perl -e \'print crypt(\"%s\", \"password\")\'' % (password),
                                     capture=True)
            else:
                password = '""' # empty means disabled

            for command in self.commands:
                execute(command.format(**locals()))
开发者ID:israelst,项目名称:vivo-scrapper,代码行数:31,代码来源:__init__.py

示例2: addkey

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def addkey(pub_file):
    '''
    fab env setup.addkey:id_rsa.pub
    '''
    f = Path(pub_file)

    if not f.exists():
        abort('Public key file not found: %s' % keyfile)

    pub_key = f.read_file().strip()

    append('~/.ssh/authorized_keys', pub_key)
开发者ID:israelst,项目名称:vivo-scrapper,代码行数:14,代码来源:__init__.py

示例3: get_thesaurus_text

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def get_thesaurus_text():
    p = Path('./thesaurus.txt')
    
    text = None
    
    if not p.exists():
        logging.info("File doesn't exist, parsing from internet")
        text = _retrieve_thesaurus_text()
        p.write_file(text.encode('utf-8')) 
    else:
        logging.info("File exists, reading in")
        text = p.read_file().decode('utf-8')
    
    logging.info("Read text length: %s" % len(text))

    return text
开发者ID:jimmytheleaf,项目名称:ThesaurusGame,代码行数:18,代码来源:thesaurus.py

示例4: id3

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def id3(audio, episode, title, image):
    """
    Update ID3 tags with episode info.
    """

    if not episode:  # Try to detect episode from audio filename
        match = re.search(r'e(\d{2,})', audio)
        if not match:
            raise click.UsageError('Could not be detected episode. Use --episode option.')
        episode = int(match.group(1))

    id3 = eyed3.load(audio)

    id3.initTag(version=ID3_V2_3)

    id3.tag.title = title
    id3.tag.artist = 'Henrique Bastos'
    id3.tag.album = 'Curto Circuito Podcast'
    id3.tag.track_num = episode
    id3.tag.genre = 'Podcast'

    if image:
        image = Path(image)
        data = image.read_file('rb')
        mime = 'image/' + image.ext[1:]

        # HACK to make APIC header readable on iTunes
        # EYED3 sets v2.3 encoding to UTF-16, but iTunes only reads LATIN-1
        from eyed3.id3 import frames
        def force_latin1(self):
            self.encoding = eyed3.id3.LATIN1_ENCODING
        setattr(frames.ImageFrame, '_initEncoding', force_latin1)

        # force mime as str because eyeD3 uses it to compose the binary header
        # PUBLISHER_LOGO == 0x14
        id3.tag.images.set(0x14, data, str(mime))

    id3.tag.save(version=ID3_V2_3)

    # Print id3
    shell(['eyeD3', audio])
开发者ID:marcialwushu,项目名称:curtopodcast,代码行数:43,代码来源:cli.py

示例5: move_to_venv

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
    def move_to_venv(self, which_one):
        """
        Moves the created config_files into the bin folder to be executed.
        Does this by first pasting all the contents of the temporary file
        into the new or existing target file and then deleting the temp file.
        """
        target = Path(self.venv_folder, self.project_name, 'bin', which_one)
        source = Path(self.install_path, which_one)
        logger.info('target: %s, move_orig: %s' % (target, source))

        if source.exists():
            logger.info('Moving %s into place ...' % which_one)
            content = source.read_file()

            #make sure the directory exists
            if not target.parent.exists():
                target.parent.mkdir(parents=True)
            target.write_file(content, 'w+')

            source.remove()

        logger.info('...done')
开发者ID:Libermentix,项目名称:project_installer,代码行数:24,代码来源:installer.py

示例6: unused_run_sphinx_doctest

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def unused_run_sphinx_doctest():
    """
    Run Sphinx doctest tests.
    Not maintained because i cannot prevent it from also trying to test
    the documents in `django_doctests` which must be tested separately.
    """
    #~ clean_sys_path()
    #~ if sys.path[0] == '':
        #~ del sys.path[0]
    #~ print sys.path
    #~ if len(sys.argv) > 1:
        #~ raise Exception("Unexpected command-line arguments %s" % sys.argv)
    onlythis = None
    #~ onlythis = 'docs/tutorials/human/index.rst'
    args = ['sphinx-build', '-b', 'doctest']
    args += ['-a']  # all files, not only outdated
    args += ['-Q']  # no output
    if not onlythis:
        args += ['-W']  # consider warnings as errors
    build_dir = env.ROOTDIR.child('docs', env.build_dir_name)
    args += [env.ROOTDIR.child('docs'), build_dir]
    if onlythis:  # test only this document
        args += [onlythis]
    #~ args = ['sphinx-build','-b','doctest',env.DOCSDIR,env.BUILDDIR]
    #~ raise Exception(' '.join(args))
    #~ env.DOCSDIR.chdir()
    #~ import os
    #~ print os.getcwd()
    exitcode = sphinx.main(args)
    if exitcode != 0:
        output = Path(build_dir, 'output.txt')
        #~ if not output.exists():
            #~ abort("Oops: no file %s" % output)
        # six.print_("arguments to spxhinx.main() were",args)
        abort("""
=======================================
Sphinx doctest failed with exit code %s
=======================================
%s""" % (exitcode, output.read_file()))
开发者ID:ManuelWeidmann,项目名称:atelier,代码行数:41,代码来源:fablib.py

示例7: append

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
    def append(self, key):
        key_path = Path(key)

        if key_path.isfile():
            with open(str(key_path)) as f:
                key = f.read()

        if key in self:
                return

        directory = Path(self.user.path, 'keydir', self.user.name,
                                         hashlib.md5(key.strip().split()[1]).hexdigest())
        directory.mkdir(parents=True)

        key_file = Path(directory, "%s.pub" % self.user.name)
        if key_file.exists() and key_file.read_file() == key:
                return

        key_file.write_file(key)

        self.user.git.commit(['keydir'],
                                                 'Added new key for user %s' % self.user.name)

        super(ListKeys, self).append(key)
开发者ID:Codevolve,项目名称:pyolite,代码行数:26,代码来源:keys.py

示例8: objects

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def objects():

    Project = rt.models.tickets.Project
    Ticket = rt.models.tickets.Ticket
    TicketStates = rt.models.tickets.TicketStates

    prj = Project(name="Lino")
    yield prj

    settings.SITE.loading_from_dump = True

    for ln in TICKETS.splitlines():
        ln = ln.strip()
        if ln:
            a = ln.split(':')
            state = TicketStates.accepted
            a2 = []
            for i in a:
                if '[closed]' in i:
                    state = TicketStates.closed
                i = i.replace('[closed]', '')
                a2.append(i.strip())
            num = a2[0][1:]
            title = a2[1]

            import lino
            fn = Path(lino.__file__).parent.parent.child('docs', 'tickets')
            fn = fn.child(num + '.rst')
            kw = dict()
            kw.update(created=datetime.datetime.fromtimestamp(fn.ctime()))
            kw.update(modified=datetime.datetime.fromtimestamp(fn.mtime()))
            kw.update(id=int(num), summary=title, project=prj, state=state)
            logger.info("%s %s", fn, kw['modified'])
            kw.update(description=fn.read_file())
            # fd = open(fn)
            yield Ticket(**kw)
开发者ID:lino-framework,项目名称:noi,代码行数:38,代码来源:linotickets.py

示例9: index

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
def index(notebook):
    #return '<h1>Hello World!</h1>'
    if notebook == None:
    	notebooks_list = db.all();
    	return render_template('index.html', notebooks=notebooks_list)
    else:
		if request.method == 'POST':
			# Check if the notebook already exists
			selected_notebook = db.search(where('slug') == notebook)
			notebook_data = {}

			if selected_notebook:
				notebook_data['title'] = selected_notebook[0].get('title')
				notebook_data['slug'] = selected_notebook[0].get('slig')
				notebook_data['desc'] = selected_notebook[0].get('desc')

				new_md_file = Path(notebooks_dir, notebook + '.md')
				new_md_file.write_file('\n'.join(request.form['content'].split('\r\n')))

				db.update({'desc':request.form['desc'], 'title':request.form['title']}, where('slug') == notebook)
			else:
				notebook_data['title'] = request.form['title']
				notebook_data['slug'] = slugify(request.form['title'])
				notebook_data['desc'] = request.form['desc']
				#notebook_data['content'] = request.form['content'].split('\r\n')
				#Create markdown file under notebooks dir
				new_md_file = Path(notebooks_dir, notebook_data['slug'] + '.md')
				new_md_file.write_file('\n'.join(request.form['content'].split('\r\n')))

				db.insert(notebook_data)
				notebook = notebook_data['slug']

			#return render_template('notebook.html', notebook=notebook_data)
			return redirect(notebook)
		else:
			notebook_data = {}
			notebook_html = ''

			mode = request.args.get('m')
			selected_notebook = db.search(where('slug') == notebook)
			notebook_path = Path(notebooks_dir, notebook + '.md')
			
			if selected_notebook:
				notebook_data['title'] = selected_notebook[0].get('title')
				notebook_data['desc'] = selected_notebook[0].get('desc')
			else:
				notebook_data['title'] = ''
				notebook_data['desc'] = ''
				notebook_data['content'] = ''

			if mode == None:
				if selected_notebook:
					if notebook_path.exists():
						notebook_html = md.markdown(notebook_path.read_file(), extras=["code-friendly", "fenced-code-blocks", "tables", "metadata", "cuddled-lists", "link-patterns"], link_patterns=link_patterns)
						notebook_data['content'] = notebook_html
					#notebook_data['content'] = '\n'.join(selected_notebook[0].get('content'))

				return render_template('notebook.html', notebook=notebook_data)
			else:
				if selected_notebook:
					if notebook_path.exists():
						notebook_html = notebook_path.read_file()
						notebook_data['content'] = notebook_html

				return render_template('notebook-edit.html', notebook=notebook_data)
开发者ID:dewang-mistry,项目名称:Graphite,代码行数:67,代码来源:app.py

示例10: test_chef

# 需要导入模块: from unipath import Path [as 别名]
# 或者: from unipath.Path import read_file [as 别名]
 def test_chef(self):
     p = Path(self.d, "swedish", "chef", "bork", "bork")
     assert p.read_file() == "bork!"
开发者ID:Mondego,项目名称:pyreco,代码行数:5,代码来源:allPythonContent.py


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