Coder Social home page Coder Social logo

prettytable's Introduction

TUTORIAL ON HOW TO USE THE PRETTYTABLE 0.6+ API

*** This tutorial is distributed with PrettyTable and is meant to serve
as a "quick start" guide for the lazy or impatient.  It is not an
exhaustive description of the whole API, and it is not guaranteed to be
100% up to date.  For more complete and update documentation, check the
PrettyTable wiki at http://code.google.com/p/prettytable/w/list ***

= Getting your data into (and out of) the table =

Let's suppose you have a shiny new PrettyTable:

from prettytable import PrettyTable
x = PrettyTable()

and you want to put some data into it.  You have a few options.

== Row by row ==

You can add data one row at a time.  To do this you can set the field names 
first using the `field_names` attribute, and then add the rows one at a time 
using the `add_row` method:

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

== Column by column ==

You can add data one column at a time as well.  To do this you use the 
`add_column` method, which takes two arguments - a string which is the name for 
the field the column you are adding corresponds to, and a list or tuple which 
contains the column data"

x.add_column("City name", 
["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"])
x.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
x.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 
1554769])
x.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 
869.4])

== Mixing and matching ==

If you really want to, you can even mix and match `add_row` and `add_column` 
and build some of your table in one way and some of it in the other.  There's a 
unit test which makes sure that doing things this way will always work out 
nicely as if you'd done it using just one of the two approaches.  Tables built 
this way are kind of confusing for other people to read, though, so don't do 
this unless you have a good reason.

== Importing data from a CSV file ==

If you have your table data in a comma separated values file (.csv), you can
read this data into a PrettyTable like this:

from prettytable import from_csv
fp = open("myfile.csv", "r")
mytable = from_csv(fp)
fp.close()

== Importing data from a database cursor ==

If you have your table data in a database which you can access using a library which confirms to the Python DB-API (e.g. an SQLite database accessible using the sqlite module), then you can build a PrettyTable using a cursor object, like this:

import sqlite3
from prettytable import from_cursor

connection = sqlite3.connect("mydb.db")
cursor = connection.cursor()
cursor.execute("SELECT field1, field2, field3 FROM my_table")
mytable = from_cursor(cursor)

== Getting data out ==

There are three ways to get data out of a PrettyTable, in increasing order of 
completeness:

  * The `del_row` method takes an integer index of a single row to delete.
  * The `clear_rows` method takes no arguments and deletes all the rows in the 
table - but keeps the field names as they were so you that you can repopulate 
it with the same kind of data.
  * The `clear` method takes no arguments and deletes all rows and all field 
names.  It's not quite the same as creating a fresh table instance, though - 
style related settings, discussed later, are maintained.

= Displaying your table in ASCII form =

PrettyTable's main goal is to let you print tables in an attractive ASCII form, 
like this:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

You can print tables like this to `stdout` or get string representations of 
them.

== Printing ==

To print a table in ASCII form, you can just do this:

print x

in Python 2.x or:

print(x)

in Python 3.x.

The old x.printt() method from versions 0.5 and earlier has been removed.

To pass options changing the look of the table, use the get_string() method
documented below:

print x.get_string()

== Stringing ==

If you don't want to actually print your table in ASCII form but just get a 
string containing what _would_ be printed if you use "print x", you can use 
the `get_string` method:

mystring = x.get_string()

This string is guaranteed to look exactly the same as what would be printed by 
doing "print x".  You can now do all the usual things you can do with a 
string, like write your table to a file or insert it into a GUI.

== Controlling which data gets displayed ==

If you like, you can restrict the output of `print x` or `x.get_string` to
only the fields or rows you like.

The `fields` argument to these methods takes a list of field names to be 
printed:

print x.get_string(fields=["City name", "Population"])

gives:

+-----------+------------+
| City name | Population |
+-----------+------------+
| Adelaide  |  1158259   |
| Brisbane  |  1857594   |
| Darwin    |   120900   |
| Hobart    |   205556   |
| Melbourne |  3806092   |
| Perth     |  1554769   |
| Sydney    |  4336374   |
+-----------+------------+

The `start` and `end` arguments take the index of the first and last row to 
print respectively.  Note that the indexing works like Python list slicing - to 
print the 2nd, 3rd and 4th rows of the table, set `start` to 1 (the first row 
is row 0, so the second is row 1) and set `end` to 4 (the index of the 4th row, 
plus 1):

print x.get_string(start=1,end=4)

prints:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Brisbane  | 5905 |    1857594 | 1146.4          |
| Darwin    | 112  |     120900 | 1714.7          |
| Hobart    | 1357 |     205556 | 619.5           |
+-----------+------+------------+-----------------+

== Changing the alignment of columns ==

By default, all columns in a table are centre aligned.

=== All columns at once ===

You can change the alignment of all the columns in a table at once by assigning 
a one character string to the `align` attribute.  The allowed strings are "l", 
"r" and "c" for left, right and centre alignment, respectively:

x.align = "r"
print x

gives:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |    1158259 |           600.5 |
|  Brisbane | 5905 |    1857594 |          1146.4 |
|    Darwin |  112 |     120900 |          1714.7 |
|    Hobart | 1357 |     205556 |           619.5 |
| Melbourne | 1566 |    3806092 |           646.9 |
|     Perth | 5386 |    1554769 |           869.4 |
|    Sydney | 2058 |    4336374 |          1214.8 |
+-----------+------+------------+-----------------+

=== One column at a time ===

You can also change the alignment of individual columns based on the 
corresponding field name by treating the `align` attribute as if it were a 
dictionary.

x.align["City name"] = "l"
x.align["Area"] = "c"
x.align["Population"] = "r"
x.align["Annual Rainfall"] = "c"
print x

gives:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |    1158259 |      600.5      |
| Brisbane  | 5905 |    1857594 |      1146.4     |
| Darwin    | 112  |     120900 |      1714.7     |
| Hobart    | 1357 |     205556 |      619.5      |
| Melbourne | 1566 |    3806092 |      646.9      |
| Perth     | 5386 |    1554769 |      869.4      |
| Sydney    | 2058 |    4336374 |      1214.8     |
+-----------+------+------------+-----------------+

== Sorting your table by a field ==

You can make sure that your ASCII tables are produced with the data sorted by 
one particular field by giving `get_string` a `sortby` keyword argument, which
 must be a string containing the name of one field.

For example, to print the example table we built earlier of Australian capital 
city data, so that the most populated city comes last, we can do this:

print x.get_string(sortby="Population")

to get

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Adelaide  | 1295 |  1158259   |      600.5      |
| Perth     | 5386 |  1554769   |      869.4      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

If we want the most populated city to come _first_, we can also give a 
`reversesort=True` argument.

If you _always_ want your tables to be sorted in a certain way, you can make 
the setting long term like this:

x.sortby = "Population"
print x
print x
print x

All three tables printed by this code will be sorted by population (you could 
do `x.reversesort = True` as well, if you wanted).  The behaviour will persist 
until you turn it off:

x.sortby = None

If you want to specify a custom sorting function, you can use the `sort_key`
keyword argument.  Pass this a function which accepts two lists of values
and returns a negative or positive value depending on whether the first list
should appeare before or after the second one.  If your table has n columns,
each list will have n+1 elements.  Each list corresponds to one row of the
table.  The first element will be whatever data is in the relevant row, in
the column specified by the `sort_by` argument.  The remaining n elements
are the data in each of the table's columns, in order, including a repeated
instance of the data in the `sort_by` column.

= Changing the appearance of your table - the easy way =

By default, PrettyTable produces ASCII tables that look like the ones used in 
SQL database shells.  But if can print them in a variety of other formats as 
well.  If the format you want to use is common, PrettyTable makes this very 
easy for you to do using the `set_style` method.  If you want to produce an 
uncommon table, you'll have to do things slightly harder (see later).

== Setting a table style ==

You can set the style for your table using the `set_style` method before any 
calls to `print` or `get_string`.  Here's how to print a table in a format 
which works nicely with Microsoft Word's "Convert to table" feature:

from prettytable import MSWORD_FRIENDLY
x.set_style(MSWORD_FRIENDLY)
print x

In addition to `MSWORD_FRIENDLY` there are currently two other in-built styles 
you can use for your tables:

  * `DEFAULT` - The default look, used to undo any style changes you may have 
made
  * `PLAIN_COLUMN` - A borderless style that works well with command line 
programs for columnar data

Other styles are likely to appear in future releases.

= Changing the appearance of your table - the hard way =

If you want to display your table in a style other than one of the in-built 
styles listed above, you'll have to set things up the hard way.

Don't worry, it's not really that hard!

== Style options ==

PrettyTable has a number of style options which control various aspects of how 
tables are displayed.  You have the freedom to set each of these options 
individually to whatever you prefer.  The `set_style` method just does this 
automatically for you.

The options are these:

  * `border` - A boolean option (must be `True` or `False`).  Controls whether 
    or not a border is drawn around the table.
  * `header` - A boolean option (must be `True` or `False`).  Controls whether 
    or not the first row of the table is a header showing the names of all the 
    fields.
  * `hrules` - Controls printing of horizontal rules after rows.  Allowed 
    values: FRAME, HEADER, ALL, NONE - note that these are variables defined
    inside the `prettytable` module so make sure you import them or use
    `prettytable.FRAME` etc.
  * `vrules` - Controls printing of vertical rules between columns.  Allowed 
    values: FRAME, ALL, NONE.
  * `int_format` - A string which controls the way integer data is printed.
    This works like: print "%<int_format>d" % data
  * `float_format` - A string which controls the way floating point data is
     printed.  This works like: print "%<int_format>f" % data
  * `padding_width` - Number of spaces on either side of column data (only used 
    if left and right paddings are None).
  * `left_padding_width` - Number of spaces on left hand side of column data.
  * `right_padding_width` - Number of spaces on right hand side of column data.
  * `vertical_char` - Single character string used to draw vertical lines.  
     Default is `|`.
  * `horizontal_char` - Single character string used to draw horizontal lines.  
     Default is `-`.
  * `junction_char` - Single character string used to draw line junctions.  
     Default is `+`.

You can set the style options to your own settings in two ways:

== Setting style options for the long term ==

If you want to print your table with a different style several times, you can 
set your option for the "long term" just by changing the appropriate 
attributes.  If you never want your tables to have borders you can do this:

x.border = False
print x
print x
print x

Neither of the 3 tables printed by this will have borders, even if you do 
things like add extra rows inbetween them.  The lack of borders will last until 
you do:

x.border = True

to turn them on again.  This sort of long term setting is exactly how 
`set_style` works.  `set_style` just sets a bunch of attributes to pre-set 
values for you.

Note that if you know what style options you want at the moment you are 
creating your table, you can specify them using keyword arguments to the 
constructor.  For example, the following two code blocks are equivalent:

x = PrettyTable()
x.border = False
x.header = False
x.padding_width = 5

x = PrettyTable(border=False, header=False, padding_width=5)

== Changing style options just once ==

If you don't want to make long term style changes by changing an attribute like 
in the previous section, you can make changes that last for just one 
``get_string`` by giving those methods keyword arguments.  To print two 
"normal" tables with one borderless table between them, you could do this:

print x
print x.get_string(border=False)
print x

= Displaying your table in HTML form =

PrettyTable will also print your tables in HTML form, as `<table>`s.  Just like 
in ASCII form, you can actually print your table - just use `print_html()` - or 
get a string representation - just use `get_html_string()`.  HTML printing 
supports the `fields`, `start`, `end`, `sortby` and `reversesort` arguments in 
exactly the same way as ASCII printing.

== Styling HTML tables ==

By default, PrettyTable outputs HTML for "vanilla" tables.  The HTML code is 
quite simple.  It looks like this:

<table>
    <tr>
        <th>City name</th>
        <th>Area</th>
        <th>Population</th>
        <th>Annual Rainfall</th>
    </tr>
    <tr>
        <td>Adelaide</td>
        <td>1295</td>
        <td>1158259</td>
        <td>600.5</td>
    <tr>
        <td>Brisbane</td>
        <td>5905</td>
        <td>1857594</td>
        <td>1146.4</td>
    ...
    ...
    ...
</table>

If you like, you can ask PrettyTable to do its best to mimick the style options 
that your table has set using inline CSS.  This is done by giving a 
`format=True` keyword argument to either the `print_html` or `get_html_string` 
methods.  Note that if you _always_ want to print formatted HTML you can do:

x.format = True

and the setting will persist until you turn it off.

Just like with ASCII tables, if you want to change the table's style for just 
one `print_html` or one `get_html_string` you can pass those methods keyword 
arguments - exactly like `print` and `get_string`.

== Setting HTML attributes ==

You can provide a dictionary of HTML attribute name/value pairs to the 
`print_html` and `get_html_string` methods using the `attributes` keyword 
argument.  This lets you specify common HTML attributes like `name`, `id` and 
`class` that can be used for linking to your tables or customising their 
appearance using CSS.  For example:

x.print_html(attributes={"name":"my_table", "class":"red_table"})

will print:

<table name="my_table" class="red_table">
    <tr>
        <th>City name</th>
        <th>Area</th>
        <th>Population</th>
        <th>Annual Rainfall</th>
    </tr>
    ...
    ...
    ...
</table>

= Miscellaneous things =

== Copying a table ==

You can call the `copy` method on a PrettyTable object without arguments to 
return an identical independent copy of the table.

If you want a copy of a PrettyTable object with just a subset of the rows,
you can use list slicing notation:

new_table = old_table[0:5]

prettytable's People

Watchers

James Cloos avatar

prettytable's Issues

Please print empty tables

We're using PrettyTable in a functional test suite of a web application.
We have a number of tests that parse HTML using xpath, construct a plain Python 
list-of-lists representation, and print it using PrettyTable.

After an upgrade to PrettyTable 0.7.1 we get test failures because empty tables 
(i.e. those that have field names, but no actual rows) no longer get printed.

The old output used to be

    +-----------------+
    | field1 | field2 |
    +-----------------+
    +-----------------+

and if was a perfectly reasonable representation of an empty table, IMHO.

I see some doubt in the new code:

        # Don't think too hard about an empty table
        # Is this the desired behaviour?  Maybe we should still print the header?
        if self.rowcount == 0:
            return ""

so here's my plea to please return the old behaviour back.

Original issue reported on code.google.com by [email protected] on 29 Mar 2013 at 12:00

Option to set column min width

Hello,

I would like to request option to set minimum column width

Sample:
x.set_field_names(["City name", "Area"])
x.add_row(["Adelaide",1295])
x.add_row(["Brisbane",5905])
x.align["City name"] = 'l'
x.min_width["City name"] = 30

Will end:
+--------------------------------+------+
| City name                      | Area |
+--------------------------------+------+
| Adelaide                       | 1295 |
| Brisbane                       | 5905 |
+--------------------------------+------+

or

set table min width and provide column to expand:
x.min_width(60, "City name")

Will give:
+---------------------------------------------------+------+
| City name                                         | Area |
+---------------------------------------------------+------+
| Adelaide                                          | 1295 |
| Brisbane                                          | 5905 |
+---------------------------------------------------+------+

Best regards

Original issue reported on code.google.com by [email protected] on 5 Oct 2012 at 6:45

Unittest failure with py3.2: prettytable_test.PrintJapanestTest

Hello,
when preparing the Debian package, and building the package in a clean chroot, 
I'm getting this error:

testPrint (prettytable_test.PrintJapanestTest) ... ERROR
testSliceAll (prettytable_test.SlicingTests) ... ok
testSliceFirstTwoRows (prettytable_test.SlicingTests) ... ok
testSliceLastTwoRows (prettytable_test.SlicingTests) ... ok
testReverseSort (prettytable_test.SortingTests) ... ok
testSortBy (prettytable_test.SortingTests) ... ok
testSortKey (prettytable_test.SortingTests) ... ok

======================================================================
ERROR: testPrint (prettytable_test.PrintJapanestTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/buildd/prettytable-0.7/prettytable_test.py", line 566, in testPrint
    print(self.x)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 108-109: 
ordinal not in range(128)

----------------------------------------------------------------------
Ran 49 tests in 0.079s

FAILED (errors=1)


which is weird, given I can run it fine outside the chroot, but I want to ask 
you if you know more.

Cheers,
Sandro

Original issue reported on code.google.com by sandro.tosi on 21 Feb 2013 at 9:39

Vertical format for tables which are too large to fit on the terminal

Sometimes tables may become too large to fit on the terminal screen, in these 
cases, it is nice to be able to print out the table in a vertical format 
(similar to MySQL's \G option)

Here's a basic function -- would you be able to incorporate some sort of 
similar functionality in prettytable?

def format_pretty_table_vertically(table):
    '''Given a PrettyTable table instance, format each row vertically (similar to mysql's \G display)'''
    formatted = []
    max_field_width = max([len(x) for x in table._field_names])
    for row_i, row in enumerate(table._rows):
        formatted.append('*************************** %i. row ***************************' % (row_i + 1, ))
        for i, field in enumerate(table._field_names):
            formatted.append("%s: %s" % (field.rjust(max_field_width), row[i]))
    return '\n'.join(formatted)

sample output:

*************************** 1. row ***************************
People Sampled: 7294
      Location: North Pole
 Min Happiness: 1.7
 Avg Happiness: 3.7
 Max Happiness: 7.3
*************************** 2. row ***************************
People Sampled: 4321
      Location: South Pole
 Min Happiness: 3.2
 Avg Happiness: 5.2
 Max Happiness: 8.6


Thanks,
Alex

Original issue reported on code.google.com by [email protected] on 18 Dec 2013 at 6:06

max_width setter don't work

Setting max_with (e.g. "my_table.max_with = 800") will cause an exception like 
this:

Traceback (most recent call last):
  ...
  File "prettytable.py", line 333, in _set_max_width
    self._validate_nonnegativeint(val)
  File "prettytable.py", line 163, in __getattr__
    raise AttributeError(name)
AttributeError: _validate_nonnegativeint

because _validate_nonnegativeint(...) is unknown in class PrettyTable.
I assume that _validate_nonnegative_int(...) is meant here.

Original issue reported on code.google.com by [email protected] on 30 Oct 2012 at 6:07

python3 support

Hi, would be nice to have python3 support!

I attached a patch made with 2to3, here is the output:
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored prettytable.py
RefactoringTool: Files that need to be modified:
RefactoringTool: prettytable.py

Original issue reported on code.google.com by [email protected] on 9 Nov 2010 at 8:21

Attachments:

slicing does not work on Python 2.4: deepcopy fails with TypeError due to function attribute _sort_key

What steps will reproduce the problem?
1. Run tests on Python 2.4

What is the expected output? What do you see instead?
Tests should pass. Instead, slicing tests fail:

+ /usr/bin/python prettytable_test.py
...............................EE...
======================================================================
ERROR: testSliceFirstTwoRows (__main__.SlicingTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "prettytable_test.py", line 192, in testSliceFirstTwoRows
    y = self.x[0:2]
  File "/builddir/build/BUILD/prettytable-0.6.1/prettytable.py", line 171, in __getitem__
    newtable = copy.deepcopy(self)
  File "/usr/lib64/python2.4/copy.py", line 204, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/usr/lib64/python2.4/copy.py", line 351, in _reconstruct
    state = deepcopy(state, memo)
  File "/usr/lib64/python2.4/copy.py", line 174, in deepcopy
    y = copier(x, memo)
  File "/usr/lib64/python2.4/copy.py", line 268, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/usr/lib64/python2.4/copy.py", line 204, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/usr/lib64/python2.4/copy.py", line 336, in _reconstruct
    y = callable(*args)
  File "/usr/lib64/python2.4/copy_reg.py", line 92, in __newobj__
    return cls.__new__(cls, *args)
TypeError: function() takes at least 2 arguments (0 given)
======================================================================
ERROR: testSliceLastTwoRows (__main__.SlicingTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "prettytable_test.py", line 201, in testSliceLastTwoRows
    y = self.x[-2:]
  File "/builddir/build/BUILD/prettytable-0.6.1/prettytable.py", line 171, in __getitem__
    newtable = copy.deepcopy(self)
  File "/usr/lib64/python2.4/copy.py", line 204, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/usr/lib64/python2.4/copy.py", line 351, in _reconstruct
    state = deepcopy(state, memo)
  File "/usr/lib64/python2.4/copy.py", line 174, in deepcopy
    y = copier(x, memo)
  File "/usr/lib64/python2.4/copy.py", line 268, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/usr/lib64/python2.4/copy.py", line 204, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/usr/lib64/python2.4/copy.py", line 336, in _reconstruct
    y = callable(*args)
  File "/usr/lib64/python2.4/copy_reg.py", line 92, in __newobj__
    return cls.__new__(cls, *args)
TypeError: function() takes at least 2 arguments (0 given)
----------------------------------------------------------------------
Ran 36 tests in 0.050s
FAILED (errors=2)

What version of the product are you using? On what operating system?
prettytable-0.6.1, python-2.4.3 (RHEL5)

Please provide any additional information below.
This patch fixes the test suite, and it should be safe to use None because 
.sort() accepts None for the key. But I think it will still break if the caller 
slices a PrettyTable with a custom sort_key set on it. It might be necessary to 
write a custom __deepcopy__ or avoid using deepcopy.

diff -ur prettytable-0.6.1.orig/prettytable.py 
prettytable-0.6.1.patched/prettytable.py
--- prettytable-0.6.1.orig/prettytable.py   2012-06-04 08:22:23.000000000 +1000
+++ prettytable-0.6.1.patched/prettytable.py    2013-11-19 08:26:01.231044684 +1000
@@ -137,7 +137,7 @@

         self._sortby = kwargs["sortby"] or None
         self._reversesort = kwargs["reversesort"] or False
-        self._sort_key = kwargs["sort_key"] or (lambda x: x)
+        self._sort_key = kwargs["sort_key"]

         self._int_format = kwargs["float_format"] or {}
         self._float_format = kwargs["float_format"] or {}

Original issue reported on code.google.com by [email protected] on 18 Nov 2013 at 10:31

Header horizontal character style customization

Hello,

I would like to create Pandoc Markdown compliant grid tables. For this I just 
need to be able to change the header horizontal character to '=' while leaving 
the table borders and column separators at '-' 

I think this small change would be an excellent addition. Thanks very much for 
your great library. 

Original issue reported on code.google.com by [email protected] on 25 Sep 2013 at 6:57

Tutorial requires revision

The tutorial on the Wiki is out of date. Atleast:

        x.set_field_align("City name", "l")

should be:

        x.align["City name"] = 'l'

There may be others too.

Cheers!

Original issue reported on code.google.com by [email protected] on 10 Aug 2012 at 2:03

Not printing out table in ordered rows

# Import the SQLite3 module
import sqlite3
db = sqlite3.connect('book.db')
db_cur = db.cursor()
db_cur.execute('''CREATE TABLE IF NOT EXISTS novel(id INTEGER PRIMARY KEY, 
title TEXT, author TEXT, year INT)''')
novel = [
    ('As I Lay Dying', 'William Faulkner', '1930'), 
    ('Lullaby', 'Chuck Palanhuik', '2003'), 
    ('Fight Club', 'Chuck Palanhuik', '2000'), 
    ('Sex','Madonna', '1998'),
    ('Survivor','Chuck Palanhuik', '2002'),
    ('Cats Cradle', 'Kurt Vonnegut', '1967'),
    ('Slaughterhouse Five', 'Kurt Vonnegut', '1956')
]

db_cur.executemany('''INSERT INTO novel("TITLE", "AUTHOR", "YEAR") 
VALUES(?,?,?)''', novel)
db.commit()


print "Operation done successfully";
from prettytable import from_db_cursor
db.execute("SELECT * FROM novel")
pt = from_db_cursor(db_cur)

db.close()     
print pt.get_string(sortby = "TITLE")



On Python 2.7, this brings back as AttributeError: 'NoneType' object has no 
attribute 'get_string'.

If I just print pt,

I get this:

+-----+---------------------+------------------+------+
|  id |        title        |      author      | year |
+-----+---------------------+------------------+------+
|  1  |    As I Lay Dying   | William Faulkner | 1930 |
|  2  |       Lullaby       | Chuck Palanhuik  | 2003 |
|  3  |      Fight Club     | Chuck Palanhuik  | 2000 |
|  4  |         Sex         |     Madonna      | 1998 |
|  5  |    As I Lay Dying   | William Faulkner | 1930 |
|  6  |       Lullaby       | Chuck Palanhuik  | 2003 |
|  7  |      Fight Club     | Chuck Palanhuik  | 2000 |
|  8  |         Sex         |     Madonna      | 1998 |
|  9  |    As I Lay Dying   | William Faulkner | 1930 |
|  10 |       Lullaby       | Chuck Palanhuik  | 2003 |

all the way to like 300. there are only seven entries.

HELP!!

Original issue reported on code.google.com by [email protected] on 18 Jan 2014 at 1:58

Please ship also CHANGELOG and prettytable_test.py

Hello,
it would be useful to have also the mentioned files in the released tarball: a 
changelog is handy to users to know what changes between releases, and a test 
unit is handy for packagers to verity the module is working all fine.

Cheers,
Sandro

Original issue reported on code.google.com by sandro.tosi on 6 May 2012 at 7:59

Chinese Display unnormal

What steps will reproduce the problem?
1.open the test script.
2.add "Chinese" colum in head
3.add more cloum "阿斯达" to each row. run the test script.

What is the expected output? What do you see instead?
+--------+------------+----------+---------+
| Kanji  |  Hiragana  | English  | Chinese |
+--------+------------+----------+---------+
|  神戸  |   こうべ   |   Kobe   |  阿斯达 |
|  京都  |  きょうと  |  Kyoto   |  阿斯达 |
|  長崎  |  ながさき  | Nagasaki |  阿斯达 |
| 名古屋 |   なごや   |  Nagoya  |  阿斯达 |
|  大阪  |  おおさか  |  Osaka   |  阿斯达 |
|  札幌  |  さっぽろ  | Sapporo  |  阿斯达 |
|  東京  | とうきょう |  Tokyo   |  阿斯达 |
|  横浜  |  よこはま  | Yokohama |  阿斯达 |
+--------+------------+----------+---------+

Instead:
+--------+------------+----------+---------+
| Kanji  |  Hiragana  | English  | Chinese |
+--------+------------+----------+---------+
|  神戸  |   こうべ   |   Kobe   |  阿斯达 |
|  京都  |  きょうと  |  Kyoto   |  阿斯达 |
|  長崎  |  ながさき  | Nagasaki |  阿斯达 |
| 名古屋 |   なごや   |  Nagoya  |  阿斯达 |
|  大阪  |  おおさか  |  Osaka   |  阿斯达 |
|  札幌  |  さっぽろ  | Sapporo  |  阿斯达 |
|  東京  | とうきょう |  Tokyo   |  阿斯达 |
|  横浜  |  よこはま  | Yokohama |  阿斯达 |
+--------+------------+----------+---------+| とうきょう |  Tokyo   |  
阿斯达 |
|  横浜  |  よこはま  | Yokohama |  阿斯达 |
+--------+------------+----------+---------+------------+----------+---------+

code(changed):
class PrintJapanestTest(unittest.TestCase):

    def setUp(self):

        self.x = PrettyTable(["Kanji", "Hiragana", "English", "Chinese"])
        self.x.add_row(["神戸", "こうべ", "Kobe", "阿斯达"])
        self.x.add_row(["京都", "きょうと", "Kyoto", "阿斯达"])
        self.x.add_row(["長崎", "ながさき", "Nagasaki", "阿斯达"])
        self.x.add_row(["名古屋", "なごや", "Nagoya", "阿斯达"])
        self.x.add_row(["大阪", "おおさか", "Osaka", "阿斯达"])
        self.x.add_row(["札幌", "さっぽろ", "Sapporo", "阿斯达"])
        self.x.add_row(["東京", "とうきょう", "Tokyo", "阿斯达"])
        self.x.add_row(["横浜", "よこはま", "Yokohama", "阿斯达"])

    def testPrint(self):
        print()
        print(self.x)

What version of the product are you using? On what operating system?
v0.7.2 Win7 x86

Please provide any additional information below.
modify the main script ,the main method to test, also has problom.
shows:
+--------------------+-------+------------+-----------------+
| City name          |  Area | Population | Annual Rainfall |
+--------------------+-------+------------+-----------------+
| Sydney             | 2058d |  4336374   |     1214.8f     |
| Perth              | 5386d |  1554769   |      869.4f     |
| Melbourne          | 1566d |  3806092   |      646.9f     |
| Hobart             | 1357d |   205556   |      619.5f     |
| Darwin啊大声大声道 | 0112d |   120900   |     1714.7f     |
| Brisbane           | 5905d |  1857594   |     1146.4f     |
| Adel我啊是         | 1295d |  1158259   |      600.5f     |
+--------------------+-------+------------+-----------------+-----------------+

extra one cloum in last row.


Original issue reported on code.google.com by [email protected] on 21 Nov 2013 at 8:43

termcolor support

would be great if you could add support for termcolor so users can pass column 
values as

from termcolor import colored
from prettytable import PrettyTable
. . .
x.add_row([colored(my_var, 'red'), ... ])

if you do that currently, the value will be highlighted, the table formatting 
however will be broken

Original issue reported on code.google.com by mockba on 23 Jan 2013 at 8:48

  • Merged into: #18

no true unicode support

What steps will reproduce the problem?
1. Use a unicode object containing non-ASCII characters anywhere in a table.

What is the expected output? What do you see instead?
Either UnicodeEncodeError or UnicodeDecodeError.

What version of the product are you using? On what operating system?
Both 0.5 and trunk.

Please provide any additional information below.
There are tons of 'unicode' function calls without the 'encoding' argument 
throughout the code, and any string or 
unicode object containing non-ASCII characters ruins everything.

Attached a very dumb patch, which just adds a little bit smarter '_unicode' and 
replaces all 'unicode' calls with 
'_unicode'.

I believe a more clever approach is possible, like converting values once 
they're being added (via constructor or 
'add_row') thus reducing number of calls to 'unicode' or whatever.

Original issue reported on code.google.com by [email protected] on 27 Apr 2010 at 4:59

Attachments:

from_html fails with tables that use colspan

What steps will reproduce the problem?

prettytable.from_html('<table><tr><td>one</td><td>two</td></tr><tr><td 
colspan="2">three</td></tr></table>')

What is the expected output? What do you see instead?

Ideally I'd hope to see a table that prints to

+---------+---------+
| Field 1 | Field 2 |
+---------+---------+
|   one   |   two   |
|       three       |
+---------+---------+

but I'd settle for

+---------+---------+
| Field 1 | Field 2 |
+---------+---------+
|   one   |   two   |
|  three  |         |
+---------+---------+

What I get instead is

Exception: Row has incorrect number of values, (actual) 1!=2 (expected)

What version of the product are you using? On what operating system?

0.7.2 on Ubuntu 13.04

Original issue reported on code.google.com by [email protected] on 26 Aug 2013 at 10:46

Field names must (not) be unique!

By design, PrettyTables forbids duplicate field names. But this very case 
naturally occurs in any table returned by an unfiltered cross product SQL 
request, e.g.:

    cursor = c.execute("SELECT * FROM foobar A, foobar B")
    t = prettytable.from_db_cursor(cursor)

Can you add an option to override the check for uniqueness?

Thanks!

Original issue reported on code.google.com by aristide.grange on 8 Oct 2013 at 7:57

Japanese text in PrettyTable

What steps will reproduce the problem?
1. Initial steps if enter asian characters (Japanese) in UTF-8
2.
3.

What is the expected output? What do you see instead?
Expected output = Asian Text
But I see question marks like the following
+----+----+
| ?? | ?? |
+----+----+
| ?? | ?? |
+----+----+


What version of the product are you using? On what operating system?
Latest

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 23 May 2012 at 6:50

Attachments:

Feature need : support break line in cell

Hi,

PrettyTable don't support breakline in cell.

I would like to do :

t.add_row(['foo', 'bar\nsecond line'])

and output :

+---+-----------+
|foo|bar        |
|   |second line|
+---+-----------+

Regards,
Stephane

Original issue reported on code.google.com by klein.stephane on 2 Mar 2010 at 4:25

preetytable can't display chinese character normally.

please save the attachment "test.ansi",and to see the displayed table in my 
console.

from prettytable import  PrettyTable
fh= open("test.ansi", "r",encoding="gbk")
header=fh.readline().strip().split(",")
x = PrettyTable(header)
x.align["乘客姓名"]="l"
for row in fh.readlines():
    x.add_row(row.strip().split(","))

print(x)

Original issue reported on code.google.com by [email protected] on 12 Apr 2014 at 7:25

Attachments:

Document printt's removal

What steps will reproduce the problem?
1. printt is gone but the tutorials still refer to it.
2. Since other code (e.g., python-socialtext) uses printt, document that printt 
was replaced by get_string.
3.

What is the expected output? What do you see instead?


What version of the product are you using? On what operating system?


Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 15 Jun 2012 at 9:56

permission on files in egg-info not group/others readable

What steps will reproduce the problem?
1. Download the package from 
https://prettytable.googlecode.com/files/prettytable-0.7.2.tar.gz
2. Extract and notice the permission for all files, especially the ones under 
prettytable.egg-info directory
3. They should be readable by group/others.

What is the expected output? What do you see instead?
rainbow:Downloads barumugam$ tar -jxf prettytable-0.7.2.tar.bz2 && ls -lrt 
prettytable-0.7.2/prettytable.egg-info/
total 32
-rw-------@ 1 barumugam  staff   12 Apr  6 18:30 top_level.txt
-rw-------@ 1 barumugam  staff    1 Apr  6 18:30 dependency_links.txt
-rw-------@ 1 barumugam  staff  220 Apr  6 18:30 SOURCES.txt
-rw-------@ 1 barumugam  staff  710 Apr  6 18:30 PKG-INFO

What version of the product are you using? On what operating system?
0.7.2
The permission is wrong in the tar file. No matter which OS we use to extract, 
the permission is wrong. Due to this issue, if we install any library using pip 
as non-root user, it fail with following error. This one occur precisely when 
we install MySQL-python using pip, wherein prettytable is one of requirements. 
The issue seem to exist even in older versions, say: 0.7.1.

  File "/tmp/tmp2wlMmf/distribute-0.6.28/pkg_resources.py", line 1320, in _get
    stream = open(path, 'rb')
IOError: [Errno 13] Permission denied: 
'/usr/local/csi/lib/python2.6/site-packages/prettytable-0.7.2-py2.6.egg-info/top
_level.txt'
/home/jenkins/workspace/csi-nova-upstream/.tox/py26/build/MySQL-python/distribut
e-0.6.28-py2.6.egg
Traceback (most recent call last):
  File "<string>", line 16, in <module>
  File "/home/jenkins/workspace/csi-nova-upstream/.tox/py26/build/MySQL-python/setup.py", line 7, in <module>
    use_setuptools()
  File "distribute_setup.py", line 145, in use_setuptools
    return _do_download(version, download_base, to_dir, download_delay)
  File "distribute_setup.py", line 125, in _do_download
    _build_egg(egg, tarball, to_dir)
  File "distribute_setup.py", line 116, in _build_egg
    raise IOError('Could not build the egg.')
IOError: Could not build the egg.

Can you please fix it or regenerate the package with right permission for these 
files?

Thank you,
Bhuvan

Original issue reported on code.google.com by [email protected] on 28 Aug 2013 at 9:13

Adding enhanced capabilty of sorting to pretty table

Hi, 

I use the pretty table and frequently find myself where I would like to sort 
the table using a key function, currently I cannot do it inside prettytable, 
and I have have to either construct it after all my sorting or deconstruct, 
sort and reconstruct the table. 

Would it be possible to add this feature? If you want I can take a crack at it 
and submit a patch. 

Thanks
Aman

Original issue reported on code.google.com by [email protected] on 6 Jan 2012 at 4:20

Sort rows before slice.

In _get_rows, a slice occurs before any sorting takes place. I expected the 
slice to occur after. I am requesting a feature that forces the sort to happen 
before the slice.

Original issue reported on code.google.com by [email protected] on 3 May 2013 at 7:57

max width of a column

A way to specify maximal width of a column would be nice. If there is more
content then space, the content should wrap to the next line.

Original issue reported on code.google.com by tibor.arpas on 13 Jun 2009 at 11:56

tr tags not closed

In 0.6-RC01, the result of get_html_string() only includes closing </tr> 
tags at the end of the header row and the end of the table.  

While suitable for browsers, the resulting html cannot be parsed by 
xml.etree for further processing.

Original issue reported on code.google.com by [email protected] on 23 Sep 2009 at 10:04

Pagination for lp

What steps will reproduce the problem?
1. pipe = subprocess.os.popen('lp','w')
2. pipe.write(table.get_string())
3. pipe.close()

What is the expected output? What do you see instead?
Headers appear on first page only. It would be nice to be able to paginate for 
some number of lines per pate

What version of the product are you using? On what operating system?
0.7.2

Please provide any additional information below.
Example of code attached. There may be a need to specify columns per page as 
well.

Original issue reported on code.google.com by [email protected] on 21 Jul 2013 at 11:06

Attachments:

Invalid parsing of keyword arguments in constructor

What steps will reproduce the problem?
1. Create a new instance with PrettyTable(border=False)
2. print the table


What is the expected output? What do you see instead?

The keyword argument `border` is ignored. I would expect a table without border 
to be printed out. Instead a table with the border is printed.



Original issue reported on code.google.com by [email protected] on 19 Jan 2013 at 11:18

Footer

It would be nice if prettytable also could print a footer for a table. In my 
case it are the totals for each column.

Original issue reported on code.google.com by [email protected] on 9 Feb 2014 at 10:09

%Ng formatting for floats not available as an option

The differences between %f and %g are described here:

http://stackoverflow.com/questions/5913102/what-is-the-difference-between-g-and-
f-in-c

I am attaching a simple program to illustrate some differences on real data.

Here is the output:

+---------------+------------------+--------------+-------------+
|       default |        floatFmt1 |    floatFmt2 |        gFmt |
+---------------+------------------+--------------+-------------+
| 123456789.123 | 123456789.123400 | 123456789.12 | 1.23457e+08 |
|      0.000122 |         0.000122 |         0.00 |    0.000122 |
|            23 |        23.000000 |        23.00 |          23 |
|    1.01010101 |         1.010101 |         1.01 |      1.0101 |
+---------------+------------------+--------------+-------------+

Original issue reported on code.google.com by [email protected] on 24 Nov 2013 at 7:16

Attachments:

The html feature will not work with flask or I am crazy

What steps will reproduce the problem?
1. install the module
2. try to use it with flask
3. get error

What is the expected output? What do you see instead?

+------+------------+---------+ | Name | Phone | Yardage | 
+------+------------+---------+ | John | 7193382296 | 27 | | John | 7193382296 
| 27 | +------+------------+---------+
What version of the product are you using? On what operating system?

Latest mac OSX
Please provide any additional information below.

Original issue reported on code.google.com by pilotkid2011 on 14 Dec 2013 at 11:24

Changes to border line styes [was: Requests for enhancement]

Hi, this is a request for an enhancement. I would like to be able to print 
these two kind of tables, but as far as I understand this is currently not 
possible with prettytable:

header1   header2  header3
===========================
 x1y1      x2y1     x3y1
 x1y2      x2y2     x3y2
 x1y3      x2y3     x3y3

i.e. only an hrule under the header (possibly, updating the character used)

And also the following syntax is quite common:

+----------------------------+
| header1   header2  header3 |
+============================+
|  x1y1      x2y1     x3y1   |
|  x1y2      x2y2     x3y2   |
|  x1y3      x2y3     x3y3   |
+----------------------------+

i.e. a frame around the table, and a different horizontal rule under the header.

Original issue reported on code.google.com by [email protected] on 19 Jan 2013 at 9:40

Add the ability to parse pretty table output back into its original format

Currently many people use pretty table to create nice ASCII tables, which is 
great, but then there is a set of people who want to read that ASCII format 
back into python. It might be useful to associate with each ASCII table 
generator class a way to reverse said ASCII table back into a dictionary.

Original issue reported on code.google.com by [email protected] on 19 Mar 2013 at 12:41

Windows installation problem

Hi,

I tried the "hard way" for installing in Windows, but, altough I can do import 
prettytable, I cannot access the inside functions neither cant do from 
prettytable import modules (tried with PrettyTable and from_db_cursor).

I am missing something?

I've just copied the folder inside site-packages, renaming it to prettytable.

Thanks in advance.
Josep

Original issue reported on code.google.com by [email protected] on 1 Oct 2013 at 10:45

Alignment by decimal point

One very useful feature for displaying numerical data is aligning on the
decimal point. Implementing this is, of course, quite nontrivial, but
prettytable would be the ideal location for such code.

Original issue reported on code.google.com by [email protected] on 26 May 2009 at 4:19

sortby misdocumented

Wiki says that sortby behaviour can be swich off by setting it to None:

The behaviour will persist until you turn it off: 
x.sortby = None

But this raises an error:

In [57]: x.sortby = None
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-57-8471354fb9c4> in <module>()
----> 1 x.sortby = None

/usr/lib/python2.7/site-packages/prettytable.pyc in _set_sortby(self, val)
    373         return self._sortby
    374     def _set_sortby(self, val):
--> 375         self._validate_option("sortby", val)
    376         self._sortby = val
    377     sortby = property(_get_sortby, _set_sortby)

/usr/lib/python2.7/site-packages/prettytable.pyc in _validate_option(self, 
option, val)
    202             self._validate_nonnegative_int(option, val)
    203         elif option in ("sortby"):
--> 204             self._validate_field_name(option, val)
    205         elif option in ("sort_key"):
    206             self._validate_function(option, val)

/usr/lib/python2.7/site-packages/prettytable.pyc in _validate_field_name(self, 
name, val)
    278             assert val in self._field_names
    279         except AssertionError:
--> 280             raise Exception("Invalid field name: %s!" % val)
    281 
    282     def _validate_all_field_names(self, name, val):

Exception: Invalid field name: None!

Original issue reported on code.google.com by [email protected] on 29 Oct 2012 at 9:02

setup.py imports wrong version of version

When installing prettytable 0.6 using setuptools on a system that already has 
prettytable 0.5 installed, I get an import error about __version__.  This is 
because setup.py tries to import __version__ from prettytable.py, but it finds 
the 0.5 prettytable.py in the path first.  The 0.5 version doesn't have 
__version__.

I think you should probably hard code the version in setup.py instead of trying 
to import it from prettytable.py.  That would fix the problem.

Original issue reported on code.google.com by [email protected] on 19 Jul 2012 at 12:03

Changing fields_names does not recompute the column widths

What steps will reproduce the problem?

import prettytable
pt = prettytable.PrettyTable('a b c'.split())
pt.add_row([1,2,3])
pt.add_row([4,5,6])

pt.printt()  # Works as expected

# Now let's change the headers...

pt.field_names = "aaa bbb ccc".split()
pt.printt()  # oops!

# This gets printed:
+---+---+---+
| aaa | bbb | ccc |
+---+---+---+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
+---+---+---+

# Setting the headers a second time fixes this issue:
pt.field_names = "aaa bbb ccc".split()
pt.printt()

+-----+-----+-----+
| aaa | bbb | ccc |
+-----+-----+-----+
|  1  |  2  |  3  |
|  4  |  5  |  6  |
+-----+-----+-----+


I believe this happens because self._recompute_widths() is called before 
setting the new value for _field_names.


Tested with:
* prettytable SVN revision 36
* Python 2.6

Original issue reported on code.google.com by denilsonsa on 17 Jan 2011 at 5:51

Bash color

Hi,

Do you think it could be easy to espace bash color codes like that ?

'\033[1;37;40mHello World\033[2;32;40m'

Cause at this time, prettytable count each characters to set column width.

Best regards,
Socketubs.

Original issue reported on code.google.com by [email protected] on 26 Oct 2012 at 9:36

Round col entries to number of significant figures

Is this something that has being considered for future versions?  It'd be 
really nice if a format spec could be supplied for the formatting of all floats 
in a column or table e.g.

my_pretty_table.float_format_spec("4.2")

Original issue reported on code.google.com by [email protected] on 28 Feb 2012 at 11:22

Get a row without fieldnames

What steps will reproduce the problem?
1.is it possible to get the row with out field name?


+-----------+------------+
| City name | Population |
+-----------+------------+
|  Brisbane |  1857594   |
|   Darwin  |   120900   |
|   Hobart  |   205556   |
|   Sydney  |  4336374   |
+-----------+------------+

if i select the 1 row it has to show only second row as output without field 
names?

print Tablename.getstring(1)
o/p:
|  Brisbane |  1857594   |

Original issue reported on code.google.com by [email protected] on 12 Dec 2013 at 9:24

NameError: name 'PrettyTable' is not defined

What steps will reproduce the problem?
1. Followed the 'hard-way installation' on Windows with python27
2. imported module like this: 'import prettytable'
3. created new instance like this: 'myTable = PrettyTable()'

=> NameError: name 'PrettyTable' is not defined

Version: Tried with RC01 and 0.7.2

What am I doing wrong here?
Thanks

Original issue reported on code.google.com by [email protected] on 26 Aug 2013 at 12:51

table.align["xyz"] = "l" doesn't work when color is added ('\033[34mxyz\033[0m') to the header fields.

What steps will reproduce the problem?
1. Set header field to left table.align["xyz"] = "l"
2. Wrap header field with ansi colors table.header(['\033[34mxyz\033[0m']) 
3. Print table

What is the expected output? What do you see instead?
All the values under field xyz should be aligned to the left, but they're 
instead aligned at the center.

What version of the product are you using? On what operating system?
Python 2.7.2 OS X 10.8.4 prettytable (0.7.2)

Please provide any additional information below.
It would be a nice feature to be able to add color to fields and values.

Original issue reported on code.google.com by [email protected] on 21 Aug 2013 at 4:26

from_csv should should take delimiter as kwarg

Hi,

I'm currently using this lib to generate pretty ascii tables.

I get my data from a csv file where the delimiter is set to ;.

So I think thwe from_csv should take an optional delimiter arg, so it does not 
need to guess the dialect. I looked at the code and here is a corrected 
function to do this. (Only the first lines of the from_csv function)

def from_csv(fp, field_names = None, delimiter=None,**kwargs):                  


    if delimiter is None:                                                           
        dialect = csv.Sniffer().sniff(fp.read(1024))                                
        fp.seek(0)                                                                  
        reader = csv.reader(fp, dialiect)                                           
    else:                                                                           
        reader = csv.reader(fp, delimiter=delimiter)

the rest is the same


Original issue reported on code.google.com by [email protected] on 10 Jun 2013 at 8:43

Code compatibility broken: set_field_names not found

What steps will reproduce the problem?
1. Install current prettytable
2. Run the following in a Python shell:
>>> import prettytable
>>> pt = prettytable.PrettyTable()
>>> pt.set_field_names
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/prettytable.py", line 163, in __getattr__
    raise AttributeError(name)
AttributeError: set_field_names


What is the expected output? What do you see instead?

This works in prettytable 0.5

Original issue reported on code.google.com by [email protected] on 21 Nov 2012 at 2:06

Global alignment setting not working

I am attaching a simple program that attempts to use the 
p.align="r"

option as described in the online tutorial:

http://code.google.com/p/prettytable/wiki/Tutorial
(under per-column settings)

However, it looks like the global setting is ignored.
I am using prettytable 0.7.2 installed via easy_install.

The output of the program is given below:

+---------------+------------------+--------------+-------------+
|       default |        floatFmt1 |    floatFmt2 |        gFmt |
+---------------+------------------+--------------+-------------+
| 123456789.123 | 123456789.123400 | 123456789.12 | 1.23457e+08 |
|      0.000122 |         0.000122 |         0.00 |    0.000122 |
|            23 |        23.000000 |        23.00 |          23 |
|    1.01010101 |         1.010101 |         1.01 |      1.0101 |
+---------------+------------------+--------------+-------------+
+---------------+------------------+--------------+-------------+
|    default    |    floatFmt1     |  floatFmt2   |     gFmt    |
+---------------+------------------+--------------+-------------+
| 123456789.123 | 123456789.123400 | 123456789.12 | 1.23457e+08 |
|    0.000122   |     0.000122     |      0.00    |   0.000122  |
|       23      |    23.000000     |     23.00    |        23   |
|   1.01010101  |     1.010101     |      1.01    |    1.0101   |
+---------------+------------------+--------------+-------------+




Original issue reported on code.google.com by [email protected] on 24 Nov 2013 at 7:21

No distinction between HTML and XHTML

If get_html_string() is called with formatted=True and there are table cells 
with line breaks in them, the returned HTML representation uses "<br/>" for 
line breaks.  This is valid XHTML but not valid HTML (which needs "<br>").  It 
should be possible for the user to select which of these they want.

Original issue reported on code.google.com by [email protected] on 22 Jan 2013 at 1:43

Optional table title

An enhancement request for an option that will cause a title to be displayed.

+--------------------------+
|        Neat Example      |
+------------+-------------+
|   Column   | And another |
+------------+-------------+


Original issue reported on code.google.com by [email protected] on 10 May 2013 at 8:13

only return printt

when i call pt.printt(sort='something')


it's only return "printt"

and it's not happen at 0.5 version


Original issue reported on code.google.com by [email protected] on 9 May 2012 at 4:55

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.