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


Python TemporaryFile.read方法代码示例

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


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

示例1: proxy_stdf

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def proxy_stdf():
    """
    Circulate stdout/stderr via a proper file object. Designed to work around a
    problem where Python nose replaces sys.stdout/stderr with a custom 'Tee'
    object that is not a file object (compatible) and thus causes a crash with
    Popen.
    """
    tmp_stdout = sys.stdout
    try:
        tmp_stdout.fileno()
    except Exception:
        tmp_stdout = TemporaryFile()

    tmp_stderr = sys.stderr
    try:
        tmp_stderr.fileno()
    except Exception:
        tmp_stderr = TemporaryFile()

    try:
        yield tmp_stdout, tmp_stderr
    finally:
        if tmp_stdout != sys.stdout:
            tmp_stdout.seek(0)
            sys.stdout.write(tmp_stdout.read().decode())
        if tmp_stderr != sys.stderr:
            tmp_stderr.seek(0)
            sys.stderr.write(tmp_stderr.read().decode())
开发者ID:marquiz,项目名称:git-buildpackage-rpm,代码行数:30,代码来源:command_wrappers.py

示例2: test_execute_commands

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
    def test_execute_commands(self):
        """Test executing arbitrary commands and logging their output."""
        # All commands succeed.
        exp = (True, [])
        log_f = TemporaryFile(prefix=self.prefix, suffix='.txt')
        obs = _execute_commands(['echo foo', 'echo bar'], log_f, 1)
        self.assertEqual(obs, exp)

        exp = ("Command:\n\necho foo\n\nStdout:\n\nfoo\n\nStderr:\n\n\n"
               "Command:\n\necho bar\n\nStdout:\n\nbar\n\nStderr:\n\n\n")
        log_f.seek(0, 0)
        obs = log_f.read()
        self.assertEqual(obs, exp)

        # One command fails.
        exp = (False, [])
        log_f = TemporaryFile(prefix=self.prefix, suffix='.txt')
        obs = _execute_commands(['echo foo', 'foobarbaz'], log_f, 1)
        self.assertEqual(obs, exp)

        exp = ("Command:\n\necho foo\n\nStdout:\n\nfoo\n\nStderr:\n\n\n"
               "Command:\n\nfoobarbaz\n\nStdout:\n\n\nStderr:\n\n\n\n")
        log_f.seek(0, 0)

        obs = sub('Stderr:\n\n.*\n\n', 'Stderr:\n\n\n\n',
                             log_f.read())
        self.assertEqual(obs, exp)
开发者ID:wasade,项目名称:automated_testing,代码行数:29,代码来源:test_run_test_suites.py

示例3: htar

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def htar(*args):
    """Run :command:`htar` with arguments.

    Parameters
    ----------
    args : :func:`tuple`
        Arguments to be passed to :command:`htar`.

    Returns
    -------
    :func:`tuple`
        The standard output and standard error from :command:`htar`.

    Raises
    ------
    KeyError
        If the :envvar:`HPSS_DIR` environment variable has not been set.
    """
    outfile = TemporaryFile()
    errfile = TemporaryFile()
    path = get_hpss_dir()
    command = [os.path.join(path, 'htar')] + list(args)
    status = call(command, stdout=outfile, stderr=errfile)
    outfile.seek(0)
    out = outfile.read()
    errfile.seek(0)
    err = errfile.read()
    outfile.close()
    errfile.close()
    return (out.decode('utf8'), err.decode('utf8'))
开发者ID:weaverba137,项目名称:hpsspy,代码行数:32,代码来源:util.py

示例4: run_process

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def run_process(cmd, timeout=10):
    """
    run process with timeout
    """
    if type(cmd) == bytes:
        cmd = cmd.decode('utf-8')
    if type(cmd) == str:
        cmd = cmd.split()
    if not timeout:
        subprocess.Popen(cmd)
        return None, None, None
    try:
        out = TemporaryFile()
        err = TemporaryFile()
        prc = subprocess.Popen(cmd, stdout=out, stderr=err)
    except:
        LOG.exception('error in run_process %s' % cmd)
        return -1, None, None
    starttime = time.time()
    while 1:
        if time.time() - starttime > timeout:
            LOG.error('run command %s timeout' % ' '.join(cmd))
            try:
                kill_prc(prc)
            except:
                pass
            return -1, None, None
        if not alive(prc):
            out.flush()
            err.flush()
            out.seek(0)
            err.seek(0)
            return prc.poll(), out.read().decode('utf-8'), err.read().decode('utf-8')
        time.sleep(0.1)
开发者ID:kdudkov,项目名称:x10_mqtt,代码行数:36,代码来源:heyu.py

示例5: generate_minion_keys

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
 def generate_minion_keys(self):
     # XXX TODO: Replace M2Crypto with PyCrypto
     # see: https://github.com/saltstack/salt/pull/1112/files
     # generate keys
     keyname = self.get_keyname()
     if not keyname:
         LOG.error("Must specify salt_id or hostname")
         return False
     gen = RSA.gen_key(2048, 1, callback=lambda x, y, z: None)
     pubpath = os.path.join(self.pki_dir, "{0}.pub".format(keyname))
     gen.save_pub_key(pubpath)
     LOG.info("public key {0}".format(pubpath))
     if self.config.get("save_keys"):
         cumask = os.umask(191)
         gen.save_key(os.path.join(self.pki_dir, "{0}.pem".format(keyname)), None)
         os.umask(cumask)
     # public key
     _pub = TemporaryFile()
     bio_pub = BIO.File(_pub)
     m2.rsa_write_pub_key(gen.rsa, bio_pub._ptr())
     _pub.seek(0)
     self.config["public_key"] = self.public_key = _pub.read()
     self.config["formatted_public_key"] = "\n".join("    {0}".format(k) for k in self.public_key.split("\n"))
     # private key
     _pem = TemporaryFile()
     bio_pem = BIO.File(_pem)
     gen.save_key_bio(bio_pem, None)
     _pem.seek(0)
     self.config["private_key"] = self.private_key = _pem.read()
     self.config["formatted_private_key"] = "\n".join("    {0}".format(k) for k in self.private_key.split("\n"))
     return True
开发者ID:michft,项目名称:shaker,代码行数:33,代码来源:__init__.py

示例6: apply

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
    def apply(self, req, proj):
        """Run this prototype on a new project.
        NOTE: If you pass in a project that isn't new, this could explode. Don't do that.
        """
        from api import TracForgeAdminSystem

        steps = TracForgeAdminSystem(self.env).get_project_setup_participants()

        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("DELETE FROM tracforge_project_log WHERE project=%s", (proj.name,))
        db.commit()

        for step in self:
            action = args = None
            if isinstance(step, dict):
                action = step["action"]
                args = step["args"]
            else:
                action, args = step

            pid = os.fork()
            if not pid:
                # o_fd, o_file = mkstemp('tracforge-step', text=True)
                # e_fd, e_file = mkstemp('tracforge-step', text=True)

                o_file = TemporaryFile(prefix="tracforge-step", bufsize=0)
                e_file = TemporaryFile(prefix="tracforge-step", bufsize=0)

                sys.stdout = o_file
                sys.stderr = e_file

                os.dup2(o_file.fileno(), 1)
                os.dup2(e_file.fileno(), 2)

                rv = steps[action]["provider"].execute_setup_action(req, proj, action, args)
                self.env.log.debug("TracForge: %s() => %r", action, rv)

                o_file.seek(0, 0)
                o_data = o_file.read()
                o_file.close()
                e_file.seek(0, 0)
                e_data = e_file.read()
                e_file.close()

                db = self.env.get_db_cnx()
                cursor = db.cursor()
                cursor.execute(
                    "INSERT INTO tracforge_project_log (project, action, args, return, stdout, stderr) VALUES (%s, %s, %s, %s, %s, %s)",
                    (proj.name, action, args, int(rv), o_data, e_data),
                )
                db.commit()
                db.close()

                os._exit(0)
        os.waitpid(pid, 0)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:58,代码来源:model.py

示例7: main

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def main():
    shell = pexpect.spawn("./miniShell")
    shell.logfile = sys.stdout

    # Test echo
    shell.sendline("echo hello")
    shell.expect("hello.*", timeout=2)

    # Test pwd
    shell.sendline("pwd")
    shell.expect("{}.*".format(os.getcwd()), timeout=2)

    # Test cd
    t = TemporaryFile()
    subprocess.call(["ls", "-l", ".."], stdout=t)
    t.seek(0)
    shell.sendline("cd ..")
    shell.sendline("ls -l")
    shell.expect(".*" + "drwxrwxr" + ".*", timeout=2)

    # Test non-existent file
    shell.sendline("loldontexist")
    shell.expect(".*in the PATH.*", timeout=2)

    # Test foreground waiting
    shell.sendline("firefox")
    shell.expect(".*EECE315.*", timeout=5)

    # Test background running
    shell.sendline("firefox &")
    shell.expect(".*EECE315.*", timeout=2)

    # Test file redirection
    shell.sendline("cd miniShell")
    if os.path.exists(TMP_FILE):
        os.remove(TMP_FILE)
    shell.sendline("ls -l .. > {}".format(TMP_FILE))
    sleep(2)
    assert os.path.exists(TMP_FILE)
    with open(TMP_FILE, "r") as f:
        f_str = f.read().strip()
    t.seek(0)
    print t.read()
    t.seek(0)
    print f_str
    assert t.read().strip() == f_str

    # Test SIGINT handler
    shell.sendline(chr(3))

    # Test quit
    shell = pexpect.spawn("./miniShell")
    shell.logfile = sys.stdout
    shell.sendline("quit")
开发者ID:Israrul786,项目名称:EECE-315-2013,代码行数:56,代码来源:func_test.py

示例8: save_submission

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def save_submission(conf, valid_repr, test_repr):
    """
    Create a submission file given a configuration dictionary and a
    representation for valid and test.

    Parameters
    ----------
    conf : WRITEME
    valid_repr : WRITEME
    test_repr : WRITEME
    """
    print '... creating zipfile'

    # Ensure the given directory is correct
    submit_dir = conf['savedir']
    if not os.path.exists(submit_dir):
        os.makedirs(submit_dir)
    elif not os.path.isdir(submit_dir):
        raise IOError('savedir %s is not a directory' % submit_dir)

    basename = os.path.join(submit_dir, conf['dataset'] + '_' + conf['expname'])

    # If there are too much features, outputs kernel matrices
    if (valid_repr.shape[1] > valid_repr.shape[0]):
        valid_repr = numpy.dot(valid_repr, valid_repr.T)
        test_repr = numpy.dot(test_repr, test_repr.T)

    # Quantitize data
    valid_repr = numpy.floor((valid_repr / valid_repr.max())*999)
    test_repr = numpy.floor((test_repr / test_repr.max())*999)

    # Store the representations in two temporary files
    valid_file = TemporaryFile()
    test_file = TemporaryFile()

    numpy.savetxt(valid_file, valid_repr, fmt="%.3f")
    numpy.savetxt(test_file, test_repr, fmt="%.3f")

    # Reread those files and put them together in a .zip
    valid_file.seek(0)
    test_file.seek(0)

    submission = zipfile.ZipFile(basename + ".zip", "w",
                                 compression=zipfile.ZIP_DEFLATED)
    submission.writestr(basename + '_valid.prepro', valid_file.read())
    submission.writestr(basename + '_final.prepro', test_file.read())

    submission.close()
    valid_file.close()
    test_file.close()
开发者ID:EderSantana,项目名称:pylearn2,代码行数:52,代码来源:utlc.py

示例9: image_register

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def image_register(request):
    params = request.GET if request.method == "GET" else request.POST

    if not ("url" in params):
        content = {"message": u"パラメータ`url`が指定されていません"}
        return Response(content, status=status.HTTP_400_BAD_REQUEST)

    try:
        image = Images.objects.get(url=params["url"])
    except ObjectDoesNotExist:
        image = Images(url=params["url"], adult_flag=False, grotesque_flag=False)

    descriptor = factory.descriptor(filepath=image.local_path)
    if descriptor == None:
        content = {"message": u"ローカルに画像が見つかりません"}
        return Response(content, status=status.HTTP_412_PRECONDITION_FAILED)
    else:
        tmp = TemporaryFile()
        try:
            np.save(tmp, descriptor)
            tmp.seek(0)

            image.description = tmp.read()
            image.save()
        finally:
            tmp.close()

        return Response(ImageMapper(image).as_dict())
开发者ID:kawaishi-ryotaro,项目名称:harmful_image_manager,代码行数:30,代码来源:views.py

示例10: pyc

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
    def pyc(self):
        ofile=TemporaryFile('w+t')
        if self.ua:
            dst=ANSWER_PATH+self.id+'.pyc'
        else:
            dst=BINARY_PATH+self.id+'.pyc'
        cmd=['python',dst]
        p=Popen(cmd,stdin=self.ifile,stdout=ofile,universal_newlines=True,
                preexec_fn=Tester.Limiter(self.lcpu,self.lmem),stderr=DEVNULL)
        p.wait()

        self.result=0
        if p.returncode==-9:
            self.result=-5
        elif p.returncode==-11:
            self.result=-6
        elif p.returncode==-25:
            self.result=-4
        elif p.returncode<0:
            self.result=-3
        else:
            ofile.seek(0)
            if self.output!=ofile.read(-1):
                self.result=-7
        
        pass
开发者ID:LiQuidFly,项目名称:OnlineJudge,代码行数:28,代码来源:judge.py

示例11: test_title

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
 def test_title(self):
     stream = TemporaryFile()
     f = formatters.TerminfoFormatter(stream, 'xterm+sl', True, 'ascii')
     f.title('TITLE')
     stream.seek(0)
     self.assertEqual(compatibility.force_bytes('\x1b]0;TITLE\x07'),
                      stream.read())
开发者ID:chutz,项目名称:snakeoil,代码行数:9,代码来源:test_formatters.py

示例12: dataentry

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
    def dataentry(self):
        self.toaster.msgblockbegin("writing to temporary file")
        f_tmp = TemporaryFile()
        try:
            total_padding = self.data.write(f_tmp)
            # comparing the files will usually be different because blocks may
            # have been written back in a different order, so cheaply just compare
            # file sizes
            self.toaster.msg("comparing file sizes")
            self.stream.seek(0, 2)
            f_tmp.seek(0, 2)
            if self.stream.tell() != f_tmp.tell():
                self.toaster.msg("original size: %i" % self.stream.tell())
                self.toaster.msg("written size:  %i" % f_tmp.tell())
                self.toaster.msg("padding:       %i" % total_padding)
                if self.stream.tell() > f_tmp.tell() or self.stream.tell() + total_padding < f_tmp.tell():
                    f_tmp.seek(0)
                    f_debug = open("debug.cgf", "wb")
                    f_debug.write(f_tmp.read(-1))
                    f_debug.close()
                    raise Exception('write check failed: file sizes differ by more than padding')
        finally:
            f_tmp.close()
        self.toaster.msgblockend()

        # spell is finished: prevent recursing into the tree
        return False
开发者ID:Alphax,项目名称:pyffi,代码行数:29,代码来源:check.py

示例13: cxx

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
    def cxx(self):
        ofile=TemporaryFile('w+t')
        if self.ua:
            bin=ANSWER_PATH+self.id+'/x'+self.id
        else:
            bin=BINARY_PATH+self.id+'/x'+self.id
        p=Popen(bin,stdin=self.ifile,stdout=ofile,universal_newlines=True,
                preexec_fn=Tester.Limiter(self.lcpu,self.lmem),stderr=DEVNULL)
        p.wait()

        self.result=0
        if p.returncode==-9:
            self.result=-5
        elif p.returncode==-11:
            self.result=-6
        elif p.returncode==-25:
            self.result=-4
        elif p.returncode<0:
            self.result=-3
        else:
            ofile.seek(0)
            out = clear(list(self.output.strip()))
            ans = clear(list(ofile.read(-1).strip()))
            len1, len2 = len(out), len(ans)
            if len1 == len2:
                for i in range(len1):
                    if str(out[i]) != str(ans[i]):
                        self.result=-7
                        print("Wrong Answer, len1 == len2")
                        break
            else:
                self.result=-7
                print("Wrong Answer, len1 != len2")
            print ("output:\n%s" % out)
            print ("ofile:\n%s" % ans)
开发者ID:BaoLearns,项目名称:Code,代码行数:37,代码来源:judge.py

示例14: graph

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def graph(request, type, show_name):
    if not has_matplotlib:
        return HttpResponse("matplotlib missing")
    graph = None  # TODO: get cached graph
    if not graph:
        graph_lock.acquire()
        tmpfile = TemporaryFile()
        figure = pyplot.figure(1, figsize=(4, 3))

        if type == "weekday":
            _weekday_graph(show_name)
        elif type == "hours":
            _hours_graph(show_name)
        elif type == "weekday_hours":
            _weekday_hours_graph(show_name)
        elif type == "time_per_episode":
            _time_per_episode_graph(show_name, figure)

        pyplot.savefig(tmpfile, format="png")
        pyplot.close(figure)
        pyplot.clf()
        tmpfile.seek(0)
        graph = tmpfile.read()
        tmpfile.close()
        graph_lock.release()
        return HttpResponse(graph, content_type="image/png")
开发者ID:xenim,项目名称:django-radioportal,代码行数:28,代码来源:graphs.py

示例15: pdf_workup

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import read [as 别名]
def pdf_workup(request, pk):

    wu = get_object_or_404(models.Workup, pk=pk)
    active_provider_type = get_object_or_404(ProviderType,
                                             pk=request.session['clintype_pk'])

    if active_provider_type.staff_view:
        data = {'workup': wu}

        template = get_template('workup/workup_body.html')
        html  = template.render(data)

        file = TemporaryFile(mode="w+b")
        pisa.CreatePDF(html.encode('utf-8'), dest=file,
                encoding='utf-8')

        file.seek(0)
        pdf = file.read()
        file.close()

        initials = ''.join(name[0].upper() for name in wu.patient.name(reverse=False, middle_short=False).split())
        formatdate = '.'.join([str(wu.clinic_day.clinic_date.month).zfill(2), str(wu.clinic_day.clinic_date.day).zfill(2), str(wu.clinic_day.clinic_date.year)])
        filename = ''.join([initials, ' (', formatdate, ')'])

        response = HttpResponse(pdf, 'application/pdf')
        response["Content-Disposition"] = "attachment; filename=%s.pdf" % (filename,)
        return response

    else:
        return HttpResponseRedirect(reverse('workup',
                                            args=(wu.id,)))
开发者ID:SaturdayNeighborhoodHealthClinic,项目名称:osler,代码行数:33,代码来源:views.py


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