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


Python TemporaryFile.write方法代码示例

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


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

示例1: main

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def main(argv):
    args = docopt(__doc__, argv=argv)

    headers = get_args_dict(args['--header'])
    if args['--size-hint']:
        headers['x-archive-size-hint'] = args['--size-hint']

    # Upload keyword arguments.
    upload_kwargs = dict(
        metadata=get_args_dict(args['--metadata']),
        headers=headers,
        debug=args['--debug'],
        queue_derive=True if args['--no-derive'] is False else False,
        ignore_preexisting_bucket=args['--ignore-bucket'],
        checksum=args['--checksum'],
        verbose=True if args['--quiet'] is False else False,
        retries=int(args['--retries']) if args['--retries'] else 0,
        retries_sleep=int(args['--sleep']),
        delete=args['--delete'],
    )

    if args['<file>'] == ['-'] and not args['-']:
        sys.stderr.write('--remote-name is required when uploading from stdin.\n')
        call(['ia', 'upload', '--help'])
        sys.exit(1)

    # Upload from stdin.
    if args['-']:
        local_file = TemporaryFile()
        local_file.write(sys.stdin.read())
        local_file.seek(0)
        _upload_files(args, args['<identifier>'], local_file, upload_kwargs)

    # Bulk upload using spreadsheet.
    elif args['--spreadsheet']:
        # Use the same session for each upload request.
        session = ArchiveSession()

        spreadsheet = csv.DictReader(open(args['--spreadsheet'], 'rU'))
        prev_identifier = None
        for row in spreadsheet:
            local_file = row['file']
            identifier = row['identifier']
            del row['file']
            del row['identifier']
            if (not identifier) and (prev_identifier):
                identifier = prev_identifier
            # TODO: Clean up how indexed metadata items are coerced
            # into metadata.
            md_args = ['{0}:{1}'.format(k.lower(), v) for (k, v) in row.items() if v]
            metadata = get_args_dict(md_args)
            upload_kwargs['metadata'].update(metadata)
            _upload_files(args, identifier, local_file, upload_kwargs, prev_identifier,
                          session)
            prev_identifier = identifier

    # Upload files.
    else:
        local_file = args['<file>']
        _upload_files(args, args['<identifier>'], local_file, upload_kwargs)
开发者ID:digikeri,项目名称:internetarchive,代码行数:62,代码来源:ia_upload.py

示例2: SeedOutput

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
class SeedOutput(object):
    def __init__(self, fd, inv, label, resp_dict):
        self.__fd = fd
        self.__inv = inv
        self.__label = label
        self.__resp_dict = resp_dict
        self.__mseed_fd = TemporaryFile()

    def write(self, data):
        self.__mseed_fd.write(data)

    def close(self):
        try:
            try:
                seed_volume = SEEDVolume(self.__inv, ORGANIZATION, self.__label,
                    self.__resp_dict)

                self.__mseed_fd.seek(0)
                for rec in MSeedInput(self.__mseed_fd):
                    seed_volume.add_data(rec)

                seed_volume.output(self.__fd)

            except (MSeedError, SEEDError, DBError), e:
                logs.error("error creating SEED volume: " + str(e))

        finally:
            self.__mseed_fd.close()
            self.__fd.close()
开发者ID:smellyfis,项目名称:seiscomp3,代码行数:31,代码来源:arclink_fetch.py

示例3: build

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
    def build (self):
        data = []
        datapath = self.home.joinpath('data.xml')
        dom = minidom.parse(datapath.absolute().as_posix())
        index = 0
        for page in dom.getElementsByTagName('page'):
            page_data = self.parse_page(page)
            page_data['page.index'] = index
            data.append(page_data)
            index += 1

        data_loader = """
(function initData(w){{
w.Sectioner = new Object();
w.Sectioner.pages = {};
Object.freeze(w.Sectioner.pages);
}})(window);
        """.format(json.dumps(data, indent=2)).encode('UTF-8')

        data_js = TemporaryFile()
        data_js.write(data_loader)
        self.compiler.add_file(data_js, 'data.js')

        for asset in dom.getElementsByTagName('asset'):
            self.parse_asset(asset)

        return data
开发者ID:atelier-cartographique,项目名称:static-sectioner,代码行数:29,代码来源:info.py

示例4: dmenu_fetch

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def dmenu_fetch(inputstr):
  t = TemporaryFile()
  t.write(bytes(inputstr, 'UTF-8'))
  t.seek(0)
  dmenu_run = subprocess.Popen(["dmenu","-b","-fn","'DejaVu Sans Mono-13'"], stdout=subprocess.PIPE, stdin=t)
  output = (dmenu_run.communicate()[0]).decode().strip()
  return output
开发者ID:acharruel,项目名称:i3conf,代码行数:9,代码来源:workspace_controller.py

示例5: temp_image

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def temp_image():
    media_dir = settings.MEDIA_ROOT
    if not os.path.exists(media_dir):
        os.makedirs(media_dir)
    temp = TemporaryFile(suffix='.jpeg', dir=media_dir)
    temp.write(base64_gif_image())
    yield File(temp)
开发者ID:cjlee112,项目名称:socraticqs2,代码行数:9,代码来源:conftest.py

示例6: _process_data_1

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
 def _process_data_1(self, cr, uid, ids, data, context):
     #try:
         fileobj = TemporaryFile('w+')        
         fileobj.write(data)
         fileobj.seek(0) 
         lines = []
         for line in fileobj.readlines():
             #log.info('++++++++++++++++\r\nline=%s' % line)
             lines = line.split(',')            
             #if len(lines) == 0: break
             if self._isnumeric(lines[0]) == True:
                 id = int(lines[0])
                 date_from = datetime.strptime(lines[1], '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d  %H:%M:%S')
                 date_to = datetime.strptime(lines[2].replace("\n",""), '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d  %H:%M:%S')               
                 #log.info('id=%s,df=%s,dt=%s' % (id, date_from, date_to))
                 #check existing
                 day = datetime.strptime(date_from, '%Y-%m-%d  %H:%M:%S').strftime('%Y-%m-%d')
                 
                 attds = self.pool.get('hr.attendance')
                 attd_ids = attds.search(cr, uid, [('employee_id','=',id),('day','=',day)], context=context)
                 
                 #log.info(attd_ids)
                 log.info('employee_id=%d,attd_ids=%s,len=%d,day=%s' % (id,attd_ids,len(attd_ids), day))                                           
                 if len(attd_ids) == 0:                        
                     attds.create(cr, uid, {'employee_id':id,'name':date_from,'action':'sign_in','source':'import'})
                     attds.create(cr, uid, {'employee_id':id,'name':date_to,'action':'sign_out','source':'import'})
             #log.info('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
         fileobj.close()
开发者ID:fofowisworkingattelenais,项目名称:modulmodul,代码行数:30,代码来源:hr_timesheet_import_att_data.py

示例7: main

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def main(number):
    """
    Generates 100 temporal files with random numbers
    """
    for x in range(100):
        f = TemporaryFile(mode="w")
        f.write(randint(100, 10000))
开发者ID:alexico,项目名称:OMSTD,代码行数:9,代码来源:lp-005-p1.py

示例8: import_lang

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
    def import_lang(self, cr, uid, ids, context=None):
        """
            Import Language
            @param cr: the current row, from the database cursor.
            @param uid: the current user’s ID for security checks.
            @param ids: the ID or list of IDs
            @param context: A standard dictionary
        """
        if context is None:
            context = {}
        import_data = self.browse(cr, uid, ids)[0]
        if import_data.overwrite:
            context.update(overwrite=True)
        fileobj = TemporaryFile('w+')
        fileobj.write(base64.decodestring(import_data.data))

        # now we determine the file format
        fileobj.seek(0)
        first_line = fileobj.readline().strip().replace('"', '').replace(' ', '')
        fileformat = first_line.endswith("type,name,res_id,src,value") and 'csv' or 'po'
        fileobj.seek(0)

        tools.trans_load_data(cr, fileobj, fileformat, import_data.code, lang_name=import_data.name, context=context)
        fileobj.close()
        return {}
开发者ID:Aravinthu,项目名称:openerp-server-6.1,代码行数:27,代码来源:base_import_language.py

示例9: exportFile

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
 def exportFile(self, oid, f=None):
     if f is None:
         f = TemporaryFile()
     elif isinstance(f, str):
         f = open(f,'w+b')
     f.write('ZEXP')
     oids = [oid]
     done_oids = {}
     done=done_oids.has_key
     load=self._storage.load
     while oids:
         oid = oids.pop(0)
         if oid in done_oids:
             continue
         done_oids[oid] = True
         try:
             p, serial = load(oid, self._version)
         except:
             logger.debug("broken reference for oid %s", repr(oid),
                          exc_info=True)
         else:
             referencesf(p, oids)
             f.writelines([oid, p64(len(p)), p])
     f.write(export_end_marker)
     return f
开发者ID:wpjunior,项目名称:proled,代码行数:27,代码来源:ExportImport.py

示例10: handle_request

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def handle_request(request, object_id, size=None):
    book = get_object_or_404(Book, pk=object_id)
    
    if size is None:
        size = request.REQUEST.get('size',None)
    
    handle_number = book.identifier.split(':')[2].replace('/', '_')
    file_name_complete = 'var/media/' + handle_number + '_' + size + '.pdf'
    file_name_inprogress = 'var/media/' + handle_number + '_' + size
    
    if os.path.exists(file_name_complete):
        print "found complete PDF"
        PDF_file = open(file_name_complete, 'r')
        return HttpResponse(File(PDF_file).readlines(), mimetype='application/pdf')
    elif os.path.exists(file_name_inprogress):
        print "found PDF in progress"
        tempfile = TemporaryFile()
        tempfile.write('PDF compilation in progress, please check back later...')
        tempfile.seek(0);
        return HttpResponse(tempfile.readlines(), mimetype='text/plain')
    else:
        # Fire the missiles
        f = open(file_name_inprogress, 'w')
        PDF_file = File(f)
        t = threading.Thread(target=compile_PDF,
                             args=[request, book, PDF_file, size])
        t.setDaemon(True)
        t.start()
        tempfile = TemporaryFile()
        tempfile.write('PDF compilation initiated, please check back later...')
        tempfile.seek(0);
        return HttpResponse(tempfile.readlines(), mimetype='text/plain')
开发者ID:pombredanne,项目名称:Cobre,代码行数:34,代码来源:pdf.py

示例11: test_read_SIFT

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
    def test_read_SIFT(self):
        f = TemporaryFile()
        f.write(
            """2 128
133.92 135.88 14.38 -2.732
 3 12 23 38 10 15 78 20 39 67 42 8 12 8 39 35 118 43 17 0
 0 1 12 109 9 2 6 0 0 21 46 22 14 18 51 19 5 9 41 52
 65 30 3 21 55 49 26 30 118 118 25 12 8 3 2 60 53 56 72 20
 7 10 16 7 88 23 13 15 12 11 11 71 45 7 4 49 82 38 38 91
 118 15 2 16 33 3 5 118 98 38 6 19 36 1 0 15 64 22 1 2
 6 11 18 61 31 3 0 6 15 23 118 118 13 0 0 35 38 18 40 96
 24 1 0 13 17 3 24 98
132.36 99.75 11.45 -2.910
 94 32 7 2 13 7 5 23 121 94 13 5 0 0 4 59 13 30 71 32
 0 6 32 11 25 32 13 0 0 16 51 5 44 50 0 3 33 55 11 9
 121 121 12 9 6 3 0 18 55 60 48 44 44 9 0 2 106 117 13 2
 1 0 1 1 37 1 1 25 80 35 15 41 121 3 0 2 14 3 2 121
 51 11 0 20 93 6 0 20 109 57 3 4 5 0 0 28 21 2 0 5
 13 12 75 119 35 0 0 13 28 14 37 121 12 0 0 21 46 5 11 93
 29 0 0 3 14 4 11 99"""
        )
        f.seek(0)
        features = feature.SIFT.fromfile(f)
        f.close()

        assert_equal(len(features), 2)
        assert_equal(len(features["data"][0]), 128)
        assert_equal(features["row"][0], 133.92)
        assert_equal(features["column"][1], 99.75)
开发者ID:Germanc,项目名称:supreme,代码行数:31,代码来源:test_SIFT.py

示例12: test_clip_to_date_one

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def test_clip_to_date_one(pcic_data_portal):
    base_url = '/data/pcds/agg/?'
    sdate = datetime(2007, 01, 01)
    params = {'from-date': sdate.strftime('%Y/%m/%d'),
              'network-name': 'RTA', 'data-format': 'csv',
              'cliptodate': 'cliptodate',
              }
    req = Request.blank(base_url + urlencode(params))

    resp = req.get_response(pcic_data_portal)
    print resp.status
    assert resp.status == '200 OK'
    t = TemporaryFile()
    t.write(resp.body)
    z = ZipFile(t, 'r')
    assert 'RTA/pondosy.csv' in z.namelist()
    f = z.open("RTA/pondosy.csv")
    [f.readline() for _ in range(10)]
    # Read through the file and ensure the no data outside of the date
    # range was returned
    reader = csv.reader(f)
    for row in reader:
        if len(row) > 0:
            d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
            assert d >= sdate
    # Check values on the first 5 just to make sure
    expected = ['2007-01-09 00:00:00',
                '2007-01-10 00:00:00',
                '2007-01-11 00:00:00',
                '2007-01-12 00:00:00',
                '2007-01-13 00:00:00']
    for exp, actual in izip(expected, reader):
        assert exp[0] == actual
开发者ID:pacificclimate,项目名称:pdp,代码行数:35,代码来源:test_functional.py

示例13: get_data_file

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
def get_data_file(cr, uid, data):
    filedata = base64.decodestring(data)
    buf = cStringIO.StringIO(filedata)

    try:
        zipf = zipfile.ZipFile(buf, 'r')
        file_name = zipf.namelist()
        if not file_name or len(file_name) > 1:
            raise osv.except_osv(_('Error'), _('The Zip file should contain only one file'))
        filedata = zipf.read(file_name[0])
        zipf.close()
    except zipfile.BadZipfile:
        pass
    buf.close()

    try:
        s_xml = SpreadsheetXML(xmlstring=filedata)
    except osv.except_osv:
        fileobj = TemporaryFile('w+b')
        fileobj.write(filedata)
        fileformat = 'csv'
    else:
        fileobj = TemporaryFile('w+')
        s_xml.to_csv(to_file=fileobj)
        fileformat = 'xml'
    fileobj.seek(0)

    return (fileobj, fileformat)
开发者ID:hectord,项目名称:unifield,代码行数:30,代码来源:lang_tools.py

示例14: MSeed4KOutput

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
class MSeed4KOutput(object):
    def __init__(self, fd):
        self.__fd = fd
        self.__mseed_fd = TemporaryFile()

    def write(self, data):
        self.__mseed_fd.write(data)

    def close(self):
        try:
            try:
                wfd = _WaveformData()

                self.__mseed_fd.seek(0)
                for rec in MSeedInput(self.__mseed_fd):
                    wfd.add_data(rec)

                wfd.output_data(self.__fd, 0)

            except (MSeedError, SEEDError, DBError), e:
                logs.error("error reblocking Mini-SEED data: " + str(e))

        finally:
            self.__mseed_fd.close()
            self.__fd.close()
开发者ID:smellyfis,项目名称:seiscomp3,代码行数:27,代码来源:arclink_fetch.py

示例15: test_read_several

# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import write [as 别名]
    def test_read_several(self):
        """Read several stanzas from file"""
        tmpf = TemporaryFile()
        tmpf.write("""\
version_header: 1

name: foo
val: 123

name: quoted
address:   "Willowglen"
\t  42 Wallaby Way
\t  Sydney

name: bar
val: 129319
""")
        tmpf.seek(0)
        s = read_stanza(tmpf)
        self.assertEquals(s, Stanza(version_header='1'))
        s = read_stanza(tmpf)
        self.assertEquals(s, Stanza(name="foo", val='123'))
        s = read_stanza(tmpf)
        self.assertEqualDiff(s.get('name'), 'quoted')
        self.assertEqualDiff(s.get('address'), '  "Willowglen"\n  42 Wallaby Way\n  Sydney')
        s = read_stanza(tmpf)
        self.assertEquals(s, Stanza(name="bar", val='129319'))
        s = read_stanza(tmpf)
        self.assertEquals(s, None)
        self.check_rio_file(tmpf)
开发者ID:Distrotech,项目名称:bzr,代码行数:32,代码来源:test_rio.py


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