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


Python NamedTemporaryFile.seek方法代码示例

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


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

示例1: generate_shscript

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def generate_shscript(args):

    """ Generate sh script input file"""

    header = """\
    #!/bin/bash
    #PBS -q {0}
    #PBS -l nodes={1}:ppn={2}:native
    #PBS -l walltime={3}
    #PBS -N {4}
    #PBS -o {4}.out
    #PBS -e {4}.err
    #PBS -A {5}
    #PBS -M {6}
    #PBS -m abe
    #PBS -V

    """.format(args.queue, args.nodes, args.ppn, args.walltime,
               args.run_name, args.account, args.email)
    header = dedent(header)

    print header + args.cmd 

    f = NamedTemporaryFile(delete=False)
    f.write(header + args.cmd)
    f.seek(0)

    # for i in f:
    #     print i.strip()
    return f.name
开发者ID:ngcrawford,项目名称:sge_cli_tools,代码行数:32,代码来源:ezQsubGordon.py

示例2: reg_code

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def reg_code():
    img, code =generate_code_image((80,30),5)
    session["code"] = code
    tp = NamedTemporaryFile()
    img.save(tp.name,format="png")
    tp.seek(0)
    return send_file(tp.name,mimetype='image/png')
开发者ID:ipconfiger,项目名称:OpenStore,代码行数:9,代码来源:index.py

示例3: create_temp_file

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
    def create_temp_file(self, edid_binary):
        edid_file = NamedTemporaryFile(delete=False)
        edid_file.write(edid_binary)
        edid_file.flush()
        edid_file.seek(0)

        return edid_file
开发者ID:sewar,项目名称:edid.tv,代码行数:9,代码来源:test_upload.py

示例4: write_temp_file

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def write_temp_file(data):
    # create a temp file for use as a config file. This should get cleaned
    # up magically at the end of the run.
    fid = NamedTemporaryFile(mode='w+b', suffix='.tmp')
    fid.write(data)
    fid.seek(0)
    return fid
开发者ID:belonesox,项目名称:python-rhsm,代码行数:9,代码来源:config-tests.py

示例5: __init__

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
 def __init__(self, srv, lookup, userdb, spconf, url, return_to, verification_endpoint="verify", cache=None, bindings=None):
     """
     Constructor for the class.
     :param srv: Usually none, but otherwise the oic server.
     :param return_to: The URL to return to after a successful
     authentication.
     """
     self.userdb = userdb
     if cache is None:
         self.cache_outstanding_queries = {}
     else:
         self.cache_outstanding_queries = cache
     UserAuthnMethod.__init__(self, srv)
     self.return_to = return_to
     self.idp_query_param = "IdpQuery"
     if bindings:
         self.bindings = bindings
     else:
         self.bindings = [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST,
                          BINDING_HTTP_ARTIFACT]
     self.verification_endpoint = verification_endpoint
     #Configurations for the SP handler. (pyOpSamlProxy.client.sp.conf)
     self.sp_conf = importlib.import_module(spconf)
     #self.sp_conf.BASE = self.sp_conf.BASE % url
     ntf = NamedTemporaryFile(suffix="pyoidc.py", delete=True)
     ntf.write("CONFIG = " + str(self.sp_conf.CONFIG).replace("%s", url))
     ntf.seek(0)
     self.sp = Saml2Client(config_file="%s" % ntf.name)
     mte = lookup.get_template("unauthorized.mako")
     argv = {
         "message": "You are not authorized!",
     }
     self.not_authorized = mte.render(**argv)
开发者ID:devel-linotp,项目名称:pyoidc,代码行数:35,代码来源:saml.py

示例6: run_as

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def run_as(user, command, *args, **kwargs):
    """
    Run a command as a particular user, using ``/etc/environment`` and optionally
    capturing and returning the output.

    Raises subprocess.CalledProcessError if command fails.

    :param str user: Username to run command as
    :param str command: Command to run
    :param list args: Additional args to pass to command
    :param dict env: Additional env variables (will be merged with ``/etc/environment``)
    :param bool capture_output: Capture and return output (default: False)
    :param str input: Stdin for command
    """
    parts = [command] + list(args)
    quoted = ' '.join("'%s'" % p for p in parts)
    env = read_etc_env()
    if 'env' in kwargs:
        env.update(kwargs['env'])
    run = check_output if kwargs.get('capture_output') else check_call
    try:
        stdin = None
        if 'input' in kwargs:
            stdin = NamedTemporaryFile()
            stdin.write(kwargs['input'])
            stdin.seek(0)
        return run(['su', user, '-c', quoted], env=env, stdin=stdin)
    finally:
        if stdin:
            stdin.close()  # this also removes tempfile
开发者ID:ktsakalozos,项目名称:jujubigdata-dev,代码行数:32,代码来源:utils.py

示例7: export

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
 def export(self, out_f=None, format='mp3'):
     out_f = _fd_or_path_or_tempfile(out_f, 'wb+')
     out_f.seek(0)
     data = NamedTemporaryFile(mode="wb", delete=False)
     
     wave_data = wave.open(data)
     wave_data.setnchannels(self.channels)
     wave_data.setsampwidth(self.sample_width)
     wave_data.setframerate(self.frame_rate)
     wave_data.setnframes(self.frame_count())
     wave_data.writeframesraw(self._data)
     wave_data.close()
     
     
     output = NamedTemporaryFile(mode="w+")
     
     # read stdin / write stdout
     subprocess.call(['ffmpeg', 
                      '-y', # always overwrite existing files
                      "-f", "wav", "-i", data.name, # input options (filename last)
                      "-f", format, output.name, # output options (filename last)
                      ], 
                     
                     # make ffmpeg shut up
                     stderr=open(os.devnull))
     
     output.seek(0)
     out_f.write(output.read())
     
     data.unlink(data.name)
     out_f.seek(0)
     return out_f
开发者ID:xuanhan863,项目名称:pydub,代码行数:34,代码来源:audio_segment.py

示例8: handle_say

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
    def handle_say(self, engine, message, cmd, args, lang='sonid26', voice='Alyona'):
        phrase = args.strip().encode('utf-8')
        if not len(phrase):
            raise Exception(
                'Введіть, що сказати!'
                'Приклад: /report Мегас поц'
            )
        tk = gtts_token.Token().calculate_token(phrase)
        query = urllib.urlencode(dict(
            MyLanguages=lang,
            MySelectedVoice=voice,
            MyTextForTTS=phrase,
            t=1,
            SendToVaaS=''
            # q=phrase,
            # ie='UTF-8',
            # tl=lang,
            # total=1,
            # textlen=len(phrase),
            # tk=tk,
            # client='t',
            # ttsspeed=0.5
        ))
        url = 'http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2.php'

        request = urllib2.Request(url, query)
        request.add_header('Referer', 'http://www.acapela-group.com/')
        # request.add_header('Accept-Encoding', 'identity;q=1, *;q=0')
        request.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36')
        # request.add_header('Range', 'bytes=0-')
        response = urllib2.urlopen(request)

        html = response.read()

        url = re.findall('http.*\.mp3', html)
        if not len(url):
            raise Exception('API послав нас нах :/')
        url = url[0]

        response = urllib2.urlopen(url.strip())
        data = response.read()

        af = NamedTemporaryFile(delete=False, suffix='.mp3')
        af.write(data)
        af.seek(0)

        af = open(af.name, 'rb')

        try:
            engine.telegram.sendAudio(
                chat_id=message.chat_id,
                audio=af,
                title=phrase
            )
            os.unlink(af.name)
            return True
        except:
            os.unlink(af.name)
            raise
        return True
开发者ID:and3rson,项目名称:nyashbot,代码行数:62,代码来源:handlers.py

示例9: main

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def main():
    """Implement the "rose config-dump" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("conf_dir", "files", "no_pretty_mode")
    opts, args = opt_parser.parse_args()
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    fs_util = FileSystemUtil(report)
    if opts.conf_dir:
        fs_util.chdir(opts.conf_dir)
    file_names = []
    if opts.files:
        file_names = opts.files
    else:
        for dirpath, dirnames, filenames in os.walk("."):
            for filename in fnmatch.filter(filenames, "rose-*.conf"):
                p = os.path.join(dirpath, filename)[2:] # remove leading ./
                file_names.append(p)
    for file_name in file_names:
        t = NamedTemporaryFile()
        node = ConfigLoader()(file_name)
        if not opts.no_pretty_mode:
            pretty_format_config(node)
        ConfigDumper()(node, t)
        t.seek(0)
        if not filecmp.cmp(t.name, file_name, shallow=False):
            report(ConfigDumpEvent(file_name))
            ConfigDumper()(node, file_name)
开发者ID:jmancell,项目名称:rose,代码行数:30,代码来源:config_dump.py

示例10: test_merge_sam

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
    def test_merge_sam():
        'It merges two sams'
        reference = NamedTemporaryFile(suffix='.sam')
        reference.write('''>SGN-U572743
atatata
>SGN-U576692
gcgc''')
        sam1 = NamedTemporaryFile(suffix='.sam')
        sam1.write('''@SQ	SN:SGN-U576692	LN:1714
@SQ	SN:SGN-U572743	LN:833
@RG	ID:g1	LB:g1	SM:g1
@RG	ID:g2	LB:g2	SM:g2
SGN-E221403	0	SGN-U576692	1416	207	168M	*	0	0	AGCCTGATAAAGGTCTGCCTACGTGTTTTAAGTGGAATCCGTTTCCCCATGTCCAAACCTTCTAAATAGTTTTTTGTGTTAGTTCTTGTATGCCACATACAAAAATTAACAAACTCTTTTGCCACATATGTTCCAGCACGTCAAAGCAACATGTATTTGAGCTACTTT	558<///[email protected];550300094>>FBF>>88>BBB200>@[email protected]@755225889>0..14444::[email protected]@[email protected];;84444<//,4,.,<<QFBB;::/,,,.69FBB>9:2/.409;@@>88.7,//55;[email protected],,093777777884241<:7	AS:i:160	XS:i:0	XF:i:3	XE:i:4	XN:i:0	RG:Z:g2
SGN-E221664	0	SGN-U572743	317	226	254M24S	*	0	0	GGATGATCTTAGAGCTGCCATTCAAAAGATGTTAGACACTCCTGGGCCATACTTGTTGGATGTGATTGTACCTCATCAGGAGCATGTTCTACCGATGATTCCCAGTGGCGGTGCTTTCAAAAATGTGATTACGGAGGGTGATGGGAGACGTTCCTATTGACTTTGAGAAGCTACATAACTAGTTCAAGGCATTGTATTATCTAAAATAAACTTAATATTTATGTTTACTTAAAAGTTTTTCATTGTGTGAAGGAAAAAAAAAAAAAAAAAAAAAAAAA	[email protected]<22-2***-,206433>:?9<,,,66:>00066=??EEAAA?B200002<<@@@=DB99777864:..0::@833099???<@488>></...<:B<<.,,[email protected]@@;;9:/9.,,,99B99233885558=?DKKKDDAA??DKBB=440/0<[email protected]@@[email protected]@@@DD:N688BBDDDBBBKKDEDDBN977?<9<111:<??==BKMPKKBB==99>QQYYYYYYYYYYYYQQ	AS:i:250	XS:i:0	XF:i:0	XE:i:7	XN:i:0	RG:Z:g1
''')
        sam1.flush()
        sam2 = NamedTemporaryFile(suffix='.sam')
        sam2.write('''@SQ	SN:SGN-U576692	LN:1714
@SQ	SN:SGN-U572743	LN:833
@RG	ID:g1	LB:g1	SM:g1
@RG	ID:g3	LB:g3	SM:g3
SGN-E200000	0	SGN-U572743	317	226	254M24S	*	0	0	GGATGATCTTAGAGKTGCCATTCAAAAGATGTTAGACACTCCTGGGCCATACTTGTTGGATGTGATTGTACCTCATCAGGAGCATGTTCTACCGATGATTCCCAGTGGCGGTGCTTTCAAAAATGTGATTACGGAGGGTGATGGGAGACGTTCCTATTGACTTTGAGAAGCTACATAACTAGTTCAAGGCATTGTATTATCTAAAATAAACTTAATATTTATGTTTACTTAAAAGTTTTTCATTGTGTGAAGGAAAAAAAAAAAAAAAAAAAAAAAAA	[email protected]<22-2***-,206433>:?9<,,,66:>00066=??EEAAA?B200002<<@@@=DB99777864:..0::@833099???<@488>></...<:B<<.,,[email protected]@@;;9:/9.,,,99B99233885558=?DKKKDDAA??DKBB=440/0<[email protected]@@[email protected]@@@DD:N688BBDDDBBBKKDEDDBN977?<9<111:<??==BKMPKKBB==99>QQYYYYYYYYYYYYQQ	AS:i:250	XS:i:0	XF:i:0	XE:i:7	XN:i:0	RG:Z:g1
SGN-E40000	0	SGN-U576692	1416	207	168M	*	0	0	AGCCTGATAAAGGTCTGCCTACGTGTTTTAAGTGGAATCCGTTTCCCCATGTCCAAACCTTCTAAATAGTTTTTTGTGTTAGTTCTTGTATGCCACATACAAAAATTAACAAACTCTTTTGCCACATATGTTCCAGCACGTCAAAGCAACATGTATTTGAGCTACTTT	558<///[email protected];550300094>>FBF>>88>BBB200>@[email protected]@755225889>0..14444::[email protected]@[email protected];;84444<//,4,.,<<QFBB;::/,,,.69FBB>9:2/.409;@@>88.7,//55;[email protected],,093777777884241<:7	AS:i:160	XS:i:0	XF:i:3	XE:i:4	XN:i:0	RG:Z:g3
''')
        sam2.flush()
        sam3	= NamedTemporaryFile(suffix='.sam')
        merge_sam(infiles=[sam1,	sam2],	outfile=sam3,	reference=reference)
        sam3.seek(0)
        sam3_content = sam3.read()

        assert	'SN:SGN-U572743'	in	sam3_content
        assert	'SGN-E200000'	in	sam3_content
        assert	'SGN-E221664'	in	sam3_content
开发者ID:BioinformaticsArchive,项目名称:franklin,代码行数:35,代码来源:sam_test.py

示例11: decrypt

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
    def decrypt(self, enctext):
        """ Decrypting an encrypted text by the use of a private key.

        :param enctext: The encrypted text as a string
        :return: The decrypted text
        """

        if self.log:
            self.log.info("input len: %d" % len(enctext))
        _, fil = make_temp("%s" % enctext, decode=False)
        ntf = NamedTemporaryFile(delete=not DEBUG)

        com_list = [self.xmlsec, "--decrypt",
                     "--privkey-pem", self.key_file,
                     "--output", ntf.name,
                     "--id-attr:%s" % ID_ATTR, ENC_KEY_CLASS,
                     fil]

        if self.debug:
            self.log.debug("Decrypt command: %s" % " ".join(com_list))

        pof = Popen(com_list, stderr=PIPE, stdout=PIPE)
        p_out = pof.stdout.read()
        p_err = pof.stderr.read()

        if self.debug:
            self.log.debug("Decrypt result (out): %s" % (p_out,))
            self.log.debug("Decrypt result (err): %s" % (p_err,))

        ntf.seek(0)
        return ntf.read()
开发者ID:FluidReview,项目名称:saml2,代码行数:33,代码来源:sigver.py

示例12: get

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
    def get(self, request, deliveryid):
        delivery = get_object_or_404(Delivery, id=deliveryid)
        assignment_group = delivery.deadline.assignment_group
        if not (assignment_group.is_candidate(request.user) \
                    or assignment_group.is_examiner(request.user) \
                    or request.user.is_superuser \
                    or assignment_group.parentnode.is_admin(request.user)):
            return HttpResponseForbidden("Forbidden")
        dirname = '{}-{}-delivery{}'.format(
                assignment_group.parentnode.get_path(),
                assignment_group.get_candidates(separator='_'),
                delivery.number)
        zip_file_name = u'{}.zip'.format(dirname)

        tempfile = NamedTemporaryFile()
        zip_file = zipfile.ZipFile(tempfile, 'w');

        for filemeta in delivery.filemetas.all():
            file_content = filemeta.deliverystore.read_open(filemeta)
            zip_file.write(file_content.name, posixpath.join(dirname, filemeta.filename))
        zip_file.close()

        tempfile.seek(0)
        response = HttpResponse(FileWrapperWithExplicitClose(tempfile),
                                content_type="application/zip")
        response['Content-Disposition'] = "attachment; filename=%s" % \
            zip_file_name.encode("ascii", 'replace')
        response['Content-Length'] = stat(tempfile.name).st_size
        return response
开发者ID:RobertKolner,项目名称:devilry-django,代码行数:31,代码来源:views.py

示例13: src_file

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def src_file():
    src = NamedTemporaryFile()
    src.write(data)
    src.flush()
    src.seek(0, SEEK_SET)

    return src
开发者ID:tebeka,项目名称:iocp,代码行数:9,代码来源:test_iocp.py

示例14: main

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def main():
    """Implement the "rose config-dump" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("conf_dir", "files", "no_pretty_mode")
    opts = opt_parser.parse_args()[0]
    verbosity = opts.verbosity - opts.quietness
    report = Reporter(verbosity)
    fs_util = FileSystemUtil(report)
    if opts.conf_dir:
        fs_util.chdir(opts.conf_dir)
    file_names = []
    if opts.files:
        file_names = opts.files
    else:
        for dirpath, _, filenames in os.walk("."):
            for filename in fnmatch.filter(filenames, "rose-*.conf"):
                path = os.path.join(dirpath, filename)[2:]  # remove leading ./
                file_names.append(path)
    for file_name in file_names:
        handle = NamedTemporaryFile()
        node = ConfigLoader()(file_name)
        if (not opts.no_pretty_mode and
                os.path.basename(file_name) != META_CONFIG_NAME):
            pretty_format_config(node, ignore_error=True)
        ConfigDumper()(node, handle)
        handle.seek(0)
        if not filecmp.cmp(handle.name, file_name, shallow=False):
            report(ConfigDumpEvent(file_name))
            ConfigDumper()(node, file_name)
开发者ID:aosprey,项目名称:rose,代码行数:31,代码来源:config_dump.py

示例15: xls_export

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import seek [as 别名]
def xls_export(request, username, id_string):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, id_string=id_string, user=owner)
    if not has_permission(xform, owner, request):
        return HttpResponseForbidden(_(u"Not shared."))
    query = request.GET.get("query")
    force_xlsx = request.GET.get("xlsx") == "true"
    xls_df_builder = XLSDataFrameBuilder(username, id_string, query)
    excel_defs = {
        "xls": {"suffix": ".xls", "mime_type": "vnd.ms-excel"},
        "xlsx": {"suffix": ".xlsx", "mime_type": "vnd.openxmlformats"},  # TODO: check xlsx mime type
    }
    ext = "xls" if not force_xlsx else "xlsx"
    if xls_df_builder.exceeds_xls_limits:
        ext = "xlsx"
    try:
        temp_file = NamedTemporaryFile(suffix=excel_defs[ext]["suffix"])
        xls_df_builder.export_to(temp_file.name)

        if request.GET.get("raw"):
            id_string = None
        response = response_with_mimetype_and_name(excel_defs[ext]["mime_type"], id_string, extension=ext)
        response.write(temp_file.read())
        temp_file.seek(0, os.SEEK_END)
        response["Content-Length"] = temp_file.tell()
        temp_file.close()
        return response
    except NoRecordsFoundError:
        return HttpResponse(_("No records found to export"))
开发者ID:Nuredin,项目名称:formhub,代码行数:31,代码来源:views.py


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