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


Python StringIO.flush方法代码示例

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


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

示例1: bookings_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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

示例2: user_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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 flush [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: generateOracleParserFile

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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

示例5: booking_bpoint_settlement_report

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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

示例6: EncodedStringIO

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
class EncodedStringIO(object):
    def __init__(self):
        self._data = StringIO()
        self.encoding = "ascii"

    def read(self):
        return self._data.read()

    def write(self, data):
        return self._data.write(data)

    def flush(self):
        self._data.flush()
开发者ID:pv,项目名称:bento,代码行数:15,代码来源:utils.py

示例7: _test_progress_bar

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
def _test_progress_bar(len):
    out = StringIO()
    fill_str = ('123456890' * (len//10))[:len]
    pb = DialogUI(out).get_progressbar('label', fill_str, maxval=10)
    pb.start()
    for x in range(11):
        pb.update(x)
        out.flush()  # needed atm
        pstr = out.getvalue()
        ok_startswith(pstr, 'label:')
        assert_in(' %d%% ' % (10*x), pstr)
        assert_in('ETA', pstr)
    pb.finish()
    ok_endswith(out.getvalue(), '\n')
开发者ID:glalteva,项目名称:datalad,代码行数:16,代码来源:test_dialog.py

示例8: captured_logging

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
def captured_logging(name=None):
    buffer = StringIO()
    logger = logging.getLogger(name)
    handlers = logger.handlers
    for handler in logger.handlers:
        logger.removeHandler(handler)
    handler = logging.StreamHandler(buffer)
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    yield buffer
    buffer.flush()
    logger.removeHandler(handler)
    for handler in handlers:
        logger.addHandler(handler)
开发者ID:CphInf,项目名称:klusta,代码行数:16,代码来源:utils.py

示例9: load_cookies_file

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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

示例10: load_cookies_file

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [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.
    """

    logging.debug("Loading cookie file %s into memory.", cookies_file)

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

示例11: _StreamCapturerBase

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
class _StreamCapturerBase(io.IOBase):
  """A base class for input/output stream capturers."""

  def __init__(self, real_stream):
    self._real_stream = real_stream
    self._capturing_stream = StringIO()

  def isatty(self, *args, **kwargs):
    return True

  def flush(self):
    self._capturing_stream.flush()
    self._real_stream.flush()

  def GetValue(self):
    return self._capturing_stream.getvalue()
开发者ID:gyaresu,项目名称:dotfiles,代码行数:18,代码来源:session_capturer.py

示例12: StdoutCapture

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
class StdoutCapture(object):
    def __init__(self):
        self.captured = StringIO()

    def start(self):
        sys.stdout = self.captured
        return self

    def stop(self):
        sys.stdout = sys.__stdout__
        return self

    def value(self):
        self.captured.flush()
        return self.captured.getvalue()

    def close(self):
        self.captured.close()
开发者ID:oinume,项目名称:tomahawk,代码行数:20,代码来源:utils.py

示例13: _test_progress_bar

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
def _test_progress_bar(backend, len, increment):
    out = StringIO()
    fill_str = ('123456890' * (len//10))[:len]
    pb = DialogUI(out).get_progressbar('label', fill_str, maxval=10, backend=backend)
    pb.start()
    # we can't increment 11 times
    for x in range(11):
        if not (increment and x == 0):
            # do not increment on 0
            pb.update(x if not increment else 1, increment=increment)
        out.flush()  # needed atm
        pstr = out.getvalue()
        if backend not in ('annex-remote',):  # no str repr
            ok_startswith(pstr.lstrip('\r'), 'label:')
            assert_re_in(r'.*\b%d%%.*' % (10*x), pstr)
        if backend == 'progressbar':
            assert_in('ETA', pstr)
    pb.finish()
    if backend not in ('annex-remote',):
        ok_endswith(out.getvalue(), '\n')
开发者ID:debanjum,项目名称:datalad,代码行数:22,代码来源:test_dialog.py

示例14: CaptureStdOut

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]
class CaptureStdOut(object):
    """
    An logger that both prints to stdout and writes to file.
    """

    def __init__(self, log_file_path = None, print_to_console = True, prefix = None):
        """
        :param log_file_path: The path to save the records, or None if you just want to keep it in memory
        :param print_to_console:
        """
        self._print_to_console = print_to_console
        if log_file_path is not None:
            # self._log_file_path = os.path.join(base_dir, log_file_path.replace('%T', now))
            make_file_dir(log_file_path)
            self.log = open(log_file_path, 'w')
        else:
            self.log = StringIO()
        self._log_file_path = log_file_path
        self.old_stdout = _ORIGINAL_STDOUT
        self.prefix = None if prefix is None else prefix

    def __enter__(self):

        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr

        sys.stdout = self
        sys.stderr = self
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.flush()
        sys.stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr
        self.close()

    def get_log_file_path(self):
        assert self._log_file_path is not None, "You never specified a path when you created this logger, so don't come back and ask for one now"
        return self._log_file_path

    def write(self, message):
        if self._print_to_console:
            self.old_stdout.write(message if self.prefix is None or message=='\n' else self.prefix+message)
        self.log.write(message)
        self.log.flush()

    def close(self):
        if self._log_file_path is not None:
            self.log.close()

    def read(self):
        if self._log_file_path is None:
            return self.log.getvalue()
        else:
            with open(self._log_file_path) as f:
                txt = f.read()
            return txt

    def __getattr__(self, item):
        return getattr(self.old_stdout, item)
开发者ID:QUVA-Lab,项目名称:artemis,代码行数:63,代码来源:display.py

示例15: debugprint

# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import flush [as 别名]

#.........这里部分代码省略.........
            order = obj.maker.fgraph.toposort()
        elif isinstance(obj, gof.FunctionGraph):
            results_to_print.extend(obj.outputs)
            profile_list.extend([None for item in obj.outputs])
            order = obj.toposort()
        elif isinstance(obj, (integer_types, float, np.ndarray)):
            print(obj)
        elif isinstance(obj, (theano.In, theano.Out)):
            results_to_print.append(obj.variable)
            profile_list.append(None)
        else:
            raise TypeError("debugprint cannot print an object of this type",
                            obj)

    scan_ops = []
    if any([p for p in profile_list if p is not None and p.fct_callcount > 0]):
        print("""
Timing Info
-----------
--> <time> <% time> - <total time> <% total time>'

<time>         computation time for this node
<% time>       fraction of total computation time for this node
<total time>   time for this node + total times for this node's ancestors
<% total time> total time for this node over total computation time

N.B.:
* Times include the node time and the function overhead.
* <total time> and <% total time> may over-count computation times
  if inputs to a node share a common ancestor and should be viewed as a
  loose upper bound. Their intended use is to help rule out potential nodes
  to remove when optimizing a graph because their <total time> is very low.
""", file=_file)

    for r, p in zip(results_to_print, profile_list):
        # Add the parent scan op to the list as well
        if (hasattr(r.owner, 'op') and
                isinstance(r.owner.op, theano.scan_module.scan_op.Scan)):
                    scan_ops.append(r)

        debugmode.debugprint(r, depth=depth, done=done, print_type=print_type,
                             file=_file, order=order, ids=ids,
                             scan_ops=scan_ops, stop_on_name=stop_on_name,
                             profile=p)

    if len(scan_ops) > 0:
        print("", file=_file)
        new_prefix = ' >'
        new_prefix_child = ' >'
        print("Inner graphs of the scan ops:", file=_file)

        for s in scan_ops:
            # prepare a dict which maps the scan op's inner inputs
            # to its outer inputs.
            if hasattr(s.owner.op, 'fn'):
                # If the op was compiled, print the optimized version.
                inner_inputs = s.owner.op.fn.maker.fgraph.inputs
            else:
                inner_inputs = s.owner.op.inputs
            outer_inputs = s.owner.inputs
            inner_to_outer_inputs = \
                dict([(inner_inputs[i], outer_inputs[o])
                      for i, o in
                      s.owner.op.var_mappings['outer_inp_from_inner_inp']
                      .items()])

            print("", file=_file)
            debugmode.debugprint(
                s, depth=depth, done=done,
                print_type=print_type,
                file=_file, ids=ids,
                scan_ops=scan_ops,
                stop_on_name=stop_on_name,
                scan_inner_to_outer_inputs=inner_to_outer_inputs)
            if hasattr(s.owner.op, 'fn'):
                # If the op was compiled, print the optimized version.
                outputs = s.owner.op.fn.maker.fgraph.outputs
            else:
                outputs = s.owner.op.outputs
            for idx, i in enumerate(outputs):

                if hasattr(i, 'owner') and hasattr(i.owner, 'op'):
                    if isinstance(i.owner.op, theano.scan_module.scan_op.Scan):
                        scan_ops.append(i)

                debugmode.debugprint(
                    r=i, prefix=new_prefix,
                    depth=depth, done=done,
                    print_type=print_type, file=_file,
                    ids=ids, stop_on_name=stop_on_name,
                    prefix_child=new_prefix_child,
                    scan_ops=scan_ops,
                    scan_inner_to_outer_inputs=inner_to_outer_inputs)

    if file is _file:
        return file
    elif file == 'str':
        return _file.getvalue()
    else:
        _file.flush()
开发者ID:JinCSU,项目名称:Theano,代码行数:104,代码来源:printing.py


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