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


Python StringIO.seek方法代码示例

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


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

示例1: test_split_good

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
    def test_split_good(self):
        source = StringIO("""@header
AGCTTTTT
+
IIIIB+++
""")
        target1 = StringIO()
        target2 = StringIO()

        srf2fastq.convert_single_to_two_fastq(source, target1, target2)

        target1.seek(0)
        lines1 = target1.readlines()
        self.assertEqual(len(lines1),4)
        self.assertEqual(lines1[0].rstrip(), '@header/1')
        self.assertEqual(lines1[1].rstrip(), 'AGCT')
        self.assertEqual(lines1[2].rstrip(), '+')
        self.assertEqual(lines1[3].rstrip(), 'IIII')

        target2.seek(0)
        lines2 = target2.readlines()
        self.assertEqual(len(lines2),4)
        self.assertEqual(lines2[0].rstrip(), '@header/2')
        self.assertEqual(lines2[1].rstrip(), 'TTTT')
        self.assertEqual(lines2[2].rstrip(), '+')
        self.assertEqual(lines2[3].rstrip(), 'B+++')
开发者ID:detrout,项目名称:htsworkflow,代码行数:28,代码来源:test_srf2fastq.py

示例2: user_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def user_report():
    strIO = None
    # Create or update view
    cursor = connection.cursor()
    sql = 'CREATE OR REPLACE VIEW accounts_emailuser_report_v AS \
            select md5(CAST((first_name,last_name,dob)AS text)) as hash,count(*) as occurence, first_name,last_name,\
            dob from accounts_emailuser group by first_name,last_name,dob;'
    cursor.execute(sql)

    users = EmailUserReport.objects.filter(occurence__gt=1)
    if users:
        strIO = StringIO()
        fieldnames = ['Occurence', 'First Name','Last Name','DOB']
        writer = csv.DictWriter(strIO, fieldnames=fieldnames)
        writer.writeheader()

        for u in users:
            info = {
                'Occurence': u.occurence,
                'First Name': u.first_name,
                'Last Name': u.last_name,
                'DOB': u.dob
            }
            writer.writerow(info)
        strIO.flush()
        strIO.seek(0)
    return strIO
开发者ID:brendanc-dpaw,项目名称:ledger,代码行数:29,代码来源:reports.py

示例3: outstanding_bookings

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def outstanding_bookings():
    try:
        outstanding = []
        today = datetime.date.today()
        for b in Booking.objects.filter(is_canceled=False,departure__gte=today).exclude(booking_type__in=['1','3']):
            if not b.paid:
                outstanding.append(b)


        strIO = StringIO()
        fieldnames = ['Confirmation Number','Customer','Campground','Arrival','Departure','Outstanding Amount']
        writer = csv.writer(strIO)
        writer.writerow(fieldnames)
        for o in outstanding:
            fullname = '{} {}'.format(o.details.get('first_name'),o.details.get('last_name'))
            writer.writerow([o.confirmation_number,fullname,o.campground.name,o.arrival.strftime('%d/%m/%Y'),o.departure.strftime('%d/%m/%Y'),o.outstanding])
        strIO.flush()
        strIO.seek(0)
        _file = strIO

        dt = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        recipients = []
        recipients = OutstandingBookingRecipient.objects.all()
        email = EmailMessage(
            'Unpaid Bookings Summary as at {}'.format(dt),
            'Unpaid Bookings as at {}'.format(dt),
            settings.DEFAULT_FROM_EMAIL,
            to=[r.email for r in recipients]if recipients else [settings.NOTIFICATION_EMAIL]
        )
        email.attach('OustandingBookings_{}.csv'.format(dt), _file.getvalue(), 'text/csv')
        email.send()
    except:
        raise
开发者ID:wilsonc86,项目名称:ledger,代码行数:35,代码来源:reports.py

示例4: test_split_at_with_header

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
    def test_split_at_with_header(self):
        source = StringIO("""@header1
AGCTTTTT
+
@IIIB+++
@header2
AGCTTTTT
+
IIIIB+++
""")
        target1 = StringIO()
        target2 = StringIO()

        srf2fastq.convert_single_to_two_fastq(source, target1, target2, header="foo_")

        target1.seek(0)
        lines1 = target1.readlines()
        self.assertEqual(len(lines1),8)
        self.assertEqual(lines1[0].rstrip(), '@foo_header1/1')
        self.assertEqual(lines1[1].rstrip(), 'AGCT')
        self.assertEqual(lines1[2].rstrip(), '+')
        self.assertEqual(lines1[3].rstrip(), '@III')

        target2.seek(0)
        lines2 = target2.readlines()
        self.assertEqual(len(lines2),8)
        self.assertEqual(lines2[0].rstrip(), '@foo_header1/2')
        self.assertEqual(lines2[1].rstrip(), 'TTTT')
        self.assertEqual(lines2[2].rstrip(), '+')
        self.assertEqual(lines2[3].rstrip(), 'B+++')
开发者ID:detrout,项目名称:htsworkflow,代码行数:32,代码来源:test_srf2fastq.py

示例5: bookings_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def bookings_report(_date):
    try:
        bpoint, cash = [], []
        bookings = Booking.objects.filter(created__date=_date)
        history_bookings = BookingHistory.objects.filter(created__date=_date)

        strIO = StringIO()
        fieldnames = ['Date','Confirmation Number','Name','Amount','Invoice','Booking Type']
        writer = csv.writer(strIO)
        writer.writerow(fieldnames)

        types = dict(Booking.BOOKING_TYPE_CHOICES)

        for b in bookings:
            b_name = u'{} {}'.format(b.details.get('first_name',''),b.details.get('last_name',''))
            created = timezone.localtime(b.created, pytz.timezone('Australia/Perth'))
            writer.writerow([created.strftime('%d/%m/%Y %H:%M:%S'),b.confirmation_number,b_name.encode('utf-8'),b.active_invoice.amount if b.active_invoice else '',b.active_invoice.reference if b.active_invoice else '', types[b.booking_type] if b.booking_type in types else b.booking_type])

        #for b in history_bookings:
        #    b_name = '{} {}'.format(b.details.get('first_name',''),b.details.get('last_name',''))
        #    writer.writerow([b.created.strftime('%d/%m/%Y %H:%M:%S'),b.booking.confirmation_number,b_name,b.invoice.amount,b.invoice.reference,'Yes'])
            

        strIO.flush()
        strIO.seek(0)
        return strIO
    except:
        raise
开发者ID:wilsonc86,项目名称:ledger,代码行数:30,代码来源:reports.py

示例6: test_contradictory_date_entries_warn

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
 def test_contradictory_date_entries_warn(self):
     """4.8.5.3 Emit warning on contradictory date entries."""
     stream = StringIO(
         wrap_document_text(construct_document_from(**{
             "Author": {
                 "ForeName": "John",
                 "LastName": "Smith"
             },
             "DateCompleted": {
                 "Year": "2011",
                 "Month": "01",
                 "Day": "01"
             },
             "DateRevised": {
                 "Year": "2010",
                 "Month": "01",
                 "Day": "01"
             },
         }))
     )
     stderr = StringIO()
     self.patch(sys, "stderr", stderr)
     result = parsexml.parse_element_tree(
         parsexml.file_to_element_tree(stream)
     )
     stderr.seek(0)
     stderr_out = stderr.read()
     self.assertThat(result["pubDate"], Is(None))
     self.assertThat(result["reviseDate"], Is(None))
     self.assertThat(stderr_out,
                     Contains("is greater than"))
开发者ID:DanielMcFall,项目名称:pubmed-retraction-analysis,代码行数:33,代码来源:test_parsexml.py

示例7: __str__

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
 def __str__(self):
     stream = StringIO()
     pprint.pprint(self.extractors, stream)
     stream.seek(0)
     template_data = stream.read()
     if template_data:
         return "%s[\n%s\n]" % (self.__class__.__name__, template_data)
     return "%s[none]" % (self.__class__.__name__)
开发者ID:scrapy,项目名称:scrapely,代码行数:10,代码来源:regionextract.py

示例8: test_show

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
 def test_show(self):
     """Establish that the show method will properly route to an
     alternate file.
     """
     sio = StringIO()
     ex = TowerCLIError("Fe fi fo fum; I smell the blood of an Englishman.")
     ex.show(file=sio)
     sio.seek(0)
     self.assertIn("Fe fi fo fum;", sio.read())
开发者ID:wenottingham,项目名称:tower-cli,代码行数:11,代码来源:test_utils_exceptions.py

示例9: generateOracleParserFile

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def generateOracleParserFile(oracle_codes):
    strIO = StringIO()
    fieldnames = ['Activity Code','Amount']
    writer = csv.writer(strIO)
    writer.writerow(fieldnames)
    for k,v in oracle_codes.items():
        if v != 0:
            writer.writerow([k,v])
    strIO.flush()
    strIO.seek(0)
    return strIO
开发者ID:wilsonc86,项目名称:ledger,代码行数:13,代码来源:utils.py

示例10: booking_bpoint_settlement_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def booking_bpoint_settlement_report(_date):
    try:
        bpoint, cash = [], []
        bpoint.extend([x for x in BpointTransaction.objects.filter(created__date=_date,response_code=0,crn1__startswith='0019').exclude(crn1__endswith='_test')])
        cash = CashTransaction.objects.filter(created__date=_date,invoice__reference__startswith='0019').exclude(type__in=['move_out','move_in'])

        strIO = StringIO()
        fieldnames = ['Payment Date','Settlement Date','Confirmation Number','Name','Type','Amount','Invoice']
        writer = csv.writer(strIO)
        writer.writerow(fieldnames)

        for b in bpoint:
            booking, invoice = None, None
            try:
                invoice = Invoice.objects.get(reference=b.crn1)
                try:
                    booking = BookingInvoice.objects.get(invoice_reference=invoice.reference).booking
                except BookingInvoice.DoesNotExist:
                    pass
                    
                if booking:
                    b_name = u'{} {}'.format(booking.details.get('first_name',''),booking.details.get('last_name',''))
                    created = timezone.localtime(b.created, pytz.timezone('Australia/Perth'))
                    writer.writerow([created.strftime('%d/%m/%Y %H:%M:%S'),b.settlement_date.strftime('%d/%m/%Y'),booking.confirmation_number,b_name.encode('utf-8'),str(b.action),b.amount,invoice.reference])
                else:
                    writer.writerow([b.created.strftime('%d/%m/%Y %H:%M:%S'),b.settlement_date.strftime('%d/%m/%Y'),'','',str(b.action),b.amount,invoice.reference])
            except Invoice.DoesNotExist:
                pass

        for b in cash:
            booking, invoice = None, None
            try:
                invoice = b.invoice 
                try:
                    booking = BookingInvoice.objects.get(invoice_reference=invoice.reference).booking
                except BookingInvoice.DoesNotExist:
                    pass
                    
                if booking:
                    b_name = u'{} {}'.format(booking.details.get('first_name',''),booking.details.get('last_name',''))
                    created = timezone.localtime(b.created, pytz.timezone('Australia/Perth'))
                    writer.writerow([created.strftime('%d/%m/%Y %H:%M:%S'),b.created.strftime('%d/%m/%Y'),booking.confirmation_number,b_name.encode('utf-8'),str(b.type),b.amount,invoice.reference])
                else:
                    writer.writerow([b.created.strftime('%d/%m/%Y %H:%M:%S'),b.created.strftime('%d/%m/%Y'),'','',str(b.type),b.amount,invoice.reference])
            except Invoice.DoesNotExist:
                pass

        strIO.flush()
        strIO.seek(0)
        return strIO
    except:
        raise
开发者ID:wilsonc86,项目名称:ledger,代码行数:54,代码来源:reports.py

示例11: test_throw_exception_if_input_data_invalid

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
    def test_throw_exception_if_input_data_invalid(self):
        """4.5.5.3 Throw exception if input data is invalid."""
        membuf = StringIO()
        membuf.write("invalid")
        membuf.seek(0)
        self.patch(sys, "stdin", membuf)

        if sys.version_info.major <= 2:
            with ExpectedException(ValueError):
                load.main()
        elif sys.version_info.major >= 3:
            with ExpectedException(json.decoder.JSONDecodeError):
                load.main()
开发者ID:DanielMcFall,项目名称:pubmed-retraction-analysis,代码行数:15,代码来源:test_importer.py

示例12: print_ascii_graph

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def print_ascii_graph(model_):
    """
    pip install img2txt.py

    python -c
    """
    from PIL import Image
    from six.moves import StringIO
    #import networkx as netx
    import copy
    model = copy.deepcopy(model_)
    assert model is not model_
    # model.graph.setdefault('graph', {})['size'] = '".4,.4"'
    model.graph.setdefault('graph', {})['size'] = '".3,.3"'
    model.graph.setdefault('graph', {})['height'] = '".3,.3"'
    pydot_graph = netx.to_pydot(model)
    png_str = pydot_graph.create_png(prog='dot')
    sio = StringIO()
    sio.write(png_str)
    sio.seek(0)
    pil_img = Image.open(sio)
    print('pil_img.size = %r' % (pil_img.size,))
    #def print_ascii_image(pil_img):
    #    img2txt = ut.import_module_from_fpath('/home/joncrall/venv/bin/img2txt.py')
    #    import sys
    #    pixel = pil_img.load()
    #    width, height = pil_img.size
    #    bgcolor = None
    #    #fill_string =
    #    img2txt.getANSIbgstring_for_ANSIcolor(img2txt.getANSIcolor_for_rgb(bgcolor))
    #    fill_string = "\x1b[49m"
    #    fill_string += "\x1b[K"          # does not move the cursor
    #    sys.stdout.write(fill_string)
    #    img_ansii_str = img2txt.generate_ANSI_from_pixels(pixel, width, height, bgcolor)
    #    sys.stdout.write(img_ansii_str)
    def print_ascii_image(pil_img):
        #https://gist.github.com/cdiener/10491632
        SC = 1.0
        GCF = 1.0
        WCF = 1.0
        img = pil_img
        S = (int(round(img.size[0] * SC * WCF * 3)), int(round(img.size[1] * SC)))
        img = np.sum( np.asarray( img.resize(S) ), axis=2)
        print('img.shape = %r' % (img.shape,))
        img -= img.min()
        chars = np.asarray(list(' .,:;irsXA253hMHGS#9B&@'))
        img = (1.0 - img / img.max()) ** GCF * (chars.size - 1)
        print( "\n".join( ("".join(r) for r in chars[img.astype(int)]) ) )
    print_ascii_image(pil_img)
    pil_img.close()
    pass
开发者ID:heroinlin,项目名称:ibeis,代码行数:53,代码来源:pgm_viz.py

示例13: load_cookies_file

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def load_cookies_file(cookies_file):
    """
    Loads the cookies file.

    We pre-pend the file with the special Netscape header because the cookie
    loader is very particular about this string.
    """

    cookies = StringIO()
    cookies.write('# Netscape HTTP Cookie File')
    cookies.write(open(cookies_file, 'rU').read())
    cookies.flush()
    cookies.seek(0)
    return cookies
开发者ID:fenglyu,项目名称:coursera,代码行数:16,代码来源:cookies.py

示例14: test_inject_yum_mirrors

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def test_inject_yum_mirrors(
    orig_repos_cfg, mirrors_dict, expected_repos_cfg,
    expected_repos_proxied_cfg
):
    my_out_fil = StringIO()
    inject_yum_mirrors(mirrors_dict, StringIO(orig_repos_cfg), my_out_fil)
    my_out_fil.seek(0)
    assert expected_repos_cfg == my_out_fil.read()
    # Test when proxies are allowed
    my_out_fil = StringIO()
    inject_yum_mirrors(
        mirrors_dict, StringIO(orig_repos_cfg), my_out_fil, True
    )
    my_out_fil.seek(0)
    assert expected_repos_proxied_cfg == my_out_fil.read()
开发者ID:oVirt,项目名称:jenkins,代码行数:17,代码来源:test_mirror_client.py

示例15: exceptions_csv

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import seek [as 别名]
def exceptions_csv():
    data = StringIO()
    writer = csv.writer(data)
    writer.writerow(["Count", "Message", "Traceback", "Nodes"])
    for exc in six.itervalues(runners.locust_runner.exceptions):
        nodes = ", ".join(exc["nodes"])
        writer.writerow([exc["count"], exc["msg"], exc["traceback"], nodes])
    
    data.seek(0)
    response = make_response(data.read())
    file_name = "exceptions_{0}.csv".format(time())
    disposition = "attachment;filename={0}".format(file_name)
    response.headers["Content-type"] = "text/csv"
    response.headers["Content-disposition"] = disposition
    return response
开发者ID:fordhurley,项目名称:locust,代码行数:17,代码来源:web.py


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