├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── setup.py └── x_x ├── __init__.py ├── _version.py ├── asciitable.py ├── compat.py ├── cursor.py └── x_x.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # Installer logs 26 | pip-log.txt 27 | pip-delete-this-directory.txt 28 | 29 | # Unit test / coverage reports 30 | htmlcov/ 31 | .tox/ 32 | .coverage 33 | .cache 34 | nosetests.xml 35 | coverage.xml 36 | 37 | # Translations 38 | *.mo 39 | 40 | # Mr Developer 41 | .mr.developer.cfg 42 | .project 43 | .pydevproject 44 | 45 | # Rope 46 | .ropeproject 47 | 48 | # Django stuff: 49 | *.log 50 | *.pot 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | 55 | # vi stuff 56 | *.swp 57 | *.swo 58 | 59 | # ignore excel files 60 | *.xls* 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst LICENSE 2 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | x_x: The Dead Guy CLI 2 | ===================== 3 | 4 | .. image:: https://badge.fury.io/py/x_x.png 5 | :target: http://badge.fury.io/py/x_x 6 | 7 | .. image:: https://pypip.in/d/x_x/badge.png 8 | :target: https://crate.io/packages/x_x/ 9 | 10 | 11 | x_x is a command line reader that displays either Excel files or CSVs in your terminal. The purpose of this is to not break the workflow of people who live on the command line and need to access a spreadsheet generated using Microsoft Excel. 12 | 13 | Install 14 | ------- 15 | 16 | The easy way: 17 | 18 | :: 19 | 20 | $ pip install x_x 21 | 22 | 23 | Or the hard way: 24 | 25 | :: 26 | 27 | $ git clone https://github.com/krockode/x_x.git && cd x_x && python setup.py install 28 | 29 | Usage 30 | ----- 31 | 32 | Installing this package gives you an ``x_x`` CLI executable. 33 | 34 | :: 35 | 36 | $ x_x --help 37 | Usage: x_x [OPTIONS] FILENAME 38 | 39 | Display Excel or CSV files directly on your terminal. The file type is 40 | guessed from file extensions, but can be overridden with the --file-type 41 | option. 42 | 43 | Options: 44 | -h, --heading INTEGER Row number containing the headings. 45 | -f, --file-type [csv|excel] Force parsing of the file to the chosen format. 46 | -d, --delimiter TEXT Delimiter (only applicable to CSV files) 47 | [default: ','] 48 | -q, --quotechar TEXT Quote character (only applicable to CSV files) 49 | [default: '"'] 50 | -e, --encoding TEXT Encoding [default: UTF-8] 51 | --version Show the version and exit. 52 | --help Show this message and exit. 53 | 54 | So, for example: 55 | 56 | :: 57 | 58 | $ x_x dead_guys.xlsx 59 | +---------------+--------------+ 60 | | A | B | 61 | +---------------+--------------+ 62 | | Person | Age at Death | 63 | | Harrold Holt | 59.0 | 64 | | Harry Houdini | 52.0 | 65 | | Howard Hughes | 70.0 | 66 | 67 | Or to specify a specific row as the header which will be visible on each page: 68 | 69 | :: 70 | 71 | $ x_x -h 0 dead_guys.xlsx 72 | +---------------+--------------+ 73 | | Person | Age at Death | 74 | +---------------+--------------+ 75 | | Harrold Holt | 59.0 | 76 | | Harry Houdini | 52.0 | 77 | | Howard Hughes | 70.0 | 78 | 79 | Weird CSVs? No problem! 80 | 81 | :: 82 | 83 | $ cat dead_guys.csv 84 | person;age_at_death 85 | Harrold Holt;59 86 | Harry Houdini;52 87 | Howard Hughes;70 88 | |Not some guy, but just a string with ; in it|;0 89 | 90 | :: 91 | 92 | $ x_x -h 0 --delimiter=';' --quotechar='|' dead_guys.csv 93 | +----------------------------------------------+--------------+ 94 | | person | age_at_death | 95 | +----------------------------------------------+--------------+ 96 | | Harrold Holt | 59 | 97 | | Harry Houdini | 52 | 98 | | Howard Hughes | 70 | 99 | | Not some guy, but just a string with ; in it | 0 | 100 | 101 | Does your CSV file not end in "csv"? Again, no problem: 102 | 103 | :: 104 | 105 | $ mv dead_guys.csv dead_guys.some_other_extension 106 | $ x_x -h 0 --file-type=csv --delimiter=';' --quotechar='|' dead_guys.some_other_extension 107 | +----------------------------------------------+--------------+ 108 | | person | age_at_death | 109 | +----------------------------------------------+--------------+ 110 | | Harrold Holt | 59 | 111 | | Harry Houdini | 52 | 112 | | Howard Hughes | 70 | 113 | | Not some guy, but just a string with ; in it | 0 | 114 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from setuptools import setup 3 | from x_x import __version__ 4 | 5 | requirements = ["xlrd", "click", "six"] 6 | 7 | if sys.version[0] == '2': 8 | requirements.append("unicodecsv") 9 | 10 | setup( 11 | name='x_x', 12 | author='Kristian Perkins', 13 | author_email='khperkins@gmail.com', 14 | version=__version__, 15 | url='http://github.com/krockode/x_x', 16 | py_modules=['x_x'], 17 | description='Excel file CLI Reader', 18 | long_description=open('README.rst').read(), 19 | license='Apache 2.0', 20 | packages=[ 21 | 'x_x', 22 | ], 23 | install_requires=requirements, 24 | entry_points=''' 25 | [console_scripts] 26 | x_x=x_x.x_x:cli 27 | ''', 28 | classifiers=( 29 | 'Environment :: Console', 30 | 'Development Status :: 3 - Alpha', 31 | 'License :: OSI Approved :: Apache Software License', 32 | ), 33 | ) 34 | -------------------------------------------------------------------------------- /x_x/__init__.py: -------------------------------------------------------------------------------- 1 | from ._version import __version__ 2 | -------------------------------------------------------------------------------- /x_x/_version.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.9' 2 | -------------------------------------------------------------------------------- /x_x/asciitable.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # asciitable.py taken from ipydb: https://github.com/jaysw/ipydb 3 | 4 | """Draw ascii tables.""" 5 | import sys 6 | 7 | from six import string_types, PY3 8 | from six.moves import zip, zip_longest 9 | 10 | from .compat import write_out 11 | 12 | 13 | def termsize(): 14 | """Try to figure out the size of the current terminal. 15 | 16 | Returns: 17 | Size of the terminal as a tuple: (height, width). 18 | """ 19 | import os 20 | env = os.environ 21 | 22 | def ioctl_GWINSZ(fd): 23 | try: 24 | import fcntl 25 | import termios 26 | import struct 27 | cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 28 | '1234')) 29 | except: 30 | return None 31 | return cr 32 | cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) 33 | if not cr: 34 | try: 35 | fd = os.open(os.ctermid(), os.O_RDONLY) 36 | cr = ioctl_GWINSZ(fd) 37 | os.close(fd) 38 | except: 39 | pass 40 | if not cr: 41 | try: 42 | cr = (env['LINES'], env['COLUMNS']) 43 | except: 44 | cr = (25, 80) 45 | return int(cr[1]), int(cr[0]) 46 | 47 | 48 | class FakedResult(object): 49 | 50 | """Utility for making an iterable look like an sqlalchemy ResultProxy.""" 51 | 52 | def __init__(self, items, headings): 53 | self.items = items 54 | self.headings = headings 55 | 56 | def __iter__(self): 57 | return iter(self.items) 58 | 59 | def keys(self): 60 | return self.headings 61 | 62 | 63 | class PivotResultSet(object): 64 | 65 | """Pivot a result set into an iterable of (fieldname, value).""" 66 | 67 | def __init__(self, rs): 68 | self.rs = rs 69 | 70 | def __iter__(self): 71 | # Note: here we 'ovewrite' ambiguous / duplicate keys 72 | # is this a bad thing? probably not? 73 | # r.items() throws exceptions from SA if there are ambiguous 74 | # columns in the select statement. 75 | return (zip(r.keys(), r.values()) for r in self.rs) 76 | 77 | def keys(self): 78 | return ['Field', 'Value'] 79 | 80 | 81 | def isublists(l, n): 82 | return zip_longest(*[iter(l)] * n) 83 | 84 | 85 | def draw(cursor, out=sys.stdout, paginate=True, max_fieldsize=100): 86 | """Render an result set as an ascii-table. 87 | 88 | Renders an SQL result set to `out`, some file-like object. 89 | Assumes that we can determine the current terminal height and 90 | width via the termsize module. 91 | 92 | Args: 93 | cursor: An iterable of rows. Each row is a list or tuple 94 | with index access to each cell. The cursor 95 | has a list/tuple of headings via cursor.keys(). 96 | out: File-like object. 97 | """ 98 | 99 | def heading_line(sizes): 100 | for size in sizes: 101 | write_out('+' + '-' * (size + 2), out) 102 | write_out('+\n', out) 103 | 104 | def draw_headings(headings, sizes): 105 | heading_line(sizes) 106 | for idx, size in enumerate(sizes): 107 | fmt = '| %%-%is ' % size 108 | write_out((fmt % headings[idx]), out) 109 | write_out('|\n', out) 110 | heading_line(sizes) 111 | 112 | cols, lines = termsize() 113 | headings = list(cursor.keys()) 114 | if PY3: 115 | heading_sizes = [len(str(x)) for x in headings] 116 | else: 117 | heading_sizes = [len(unicode(x)) for x in headings] 118 | if paginate: 119 | cursor = isublists(cursor, lines - 4) 120 | # else we assume cursor arrive here pre-paginated 121 | for screenrows in cursor: 122 | sizes = heading_sizes[:] 123 | for row in screenrows: 124 | if row is None: 125 | break 126 | for idx, value in enumerate(row): 127 | if not isinstance(value, string_types): 128 | if PY3: 129 | value = str(value) 130 | else: 131 | value = unicode(value) 132 | size = max(sizes[idx], len(value)) 133 | sizes[idx] = min(size, max_fieldsize) 134 | draw_headings(headings, sizes) 135 | for rw in screenrows: 136 | if rw is None: 137 | break # from isublists impl 138 | for idx, size in enumerate(sizes): 139 | fmt = '| %%-%is ' % size 140 | if idx < len(rw): 141 | value = rw[idx] 142 | if not isinstance(value, string_types): 143 | if PY3: 144 | value = str(value) 145 | else: 146 | value = unicode(value) 147 | if len(value) > max_fieldsize: 148 | value = value[:max_fieldsize - 5] + '[...]' 149 | value = value.replace('\n', '^') 150 | value = value.replace('\r', '^').replace('\t', ' ') 151 | value = fmt % value 152 | try: 153 | value = value.encode('utf-8', 'replace') 154 | except UnicodeDecodeError: 155 | value = fmt % '?' 156 | write_out(value, out) 157 | write_out('|\n', out) 158 | if not paginate: 159 | heading_line(sizes) 160 | write_out('|\n', out) 161 | 162 | out.stdin.flush() 163 | out.stdin.close() 164 | -------------------------------------------------------------------------------- /x_x/compat.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import codecs 3 | from six import PY3 4 | from contextlib import contextmanager 5 | from subprocess import Popen, PIPE 6 | 7 | if PY3: 8 | import csv 9 | else: 10 | import unicodecsv as csv 11 | 12 | 13 | def open_file(filename, encoding): 14 | """For opening files for reading with a specified encoding (usually UTF-8)""" 15 | if PY3: 16 | return open(filename, encoding=encoding) 17 | else: 18 | return codecs.open(filename, "r", encoding) 19 | 20 | 21 | def write_out(s, out, encoding="utf-8"): 22 | """Provides 2 vs 3 compatibility for writing to ``out``""" 23 | try: 24 | if PY3: 25 | if isinstance(s, bytes): 26 | out.stdin.write(s) 27 | else: 28 | out.stdin.write(bytes(s, encoding)) 29 | else: 30 | out.stdin.write(s) 31 | except IOError: 32 | exit() 33 | 34 | 35 | @contextmanager 36 | def out_py2(): 37 | """Wrapping our call to ``less`` via ``Popen`` into a basic context manager for Python 2""" 38 | out = Popen('less -FXRiS', shell=True, bufsize=0, stdin=PIPE) 39 | yield out 40 | out.wait() 41 | 42 | 43 | def out_proc(): 44 | """A context-enabled call to Popen""" 45 | if PY3: 46 | return Popen('less -FXRiS', shell=True, bufsize=0, stdin=PIPE) 47 | else: 48 | return out_py2() 49 | -------------------------------------------------------------------------------- /x_x/cursor.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import string 3 | 4 | 5 | class XCursor(object): 6 | 7 | def __init__(self, sheet, headingrow=None): 8 | self.headingrow = headingrow 9 | self.sheet = sheet 10 | 11 | def num_rows(self): 12 | return self.sheet.nrows 13 | 14 | def num_cols(self): 15 | if self.headingrow is None: 16 | return len(self.sheet_row(0)) 17 | else: 18 | return len(self.sheet_row(self.headingrow)) 19 | 20 | def sheet_row(self, n): 21 | return [c.value for c in self.sheet.row(n)] 22 | 23 | def keys(self): 24 | if self.headingrow is not None: 25 | return self.sheet_row(self.headingrow) 26 | else: 27 | u = string.ascii_uppercase 28 | return [''.join(r) for idx, r in 29 | enumerate(itertools.chain(u, itertools.product(u, u))) 30 | if idx < self.num_cols()] 31 | 32 | def __iter__(self): 33 | start = self.headingrow + 1 if self.headingrow is not None else 0 34 | return (self.sheet_row(n) for n in range(start, self.num_rows())) 35 | 36 | 37 | class CSVCursor(XCursor): 38 | 39 | def sheet_row(self, n): 40 | return self.sheet[n] 41 | 42 | def num_rows(self): 43 | return len(self.sheet) 44 | -------------------------------------------------------------------------------- /x_x/x_x.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | import string 4 | import itertools 5 | import click 6 | import xlrd 7 | import os 8 | import sys 9 | 10 | from . import asciitable, __version__ 11 | from .compat import open_file, csv, out_proc 12 | from .cursor import XCursor, CSVCursor 13 | from six import PY3 14 | from subprocess import Popen, PIPE 15 | 16 | 17 | @click.command() 18 | @click.option('--heading', 19 | '-h', 20 | type=int, 21 | help='Row number containing the headings.') 22 | @click.option("--file-type", "-f", type=click.Choice(["csv", "excel"]), 23 | help="Force parsing of the file to the chosen format.") 24 | @click.option("--delimiter", "-d", type=str, default=",", 25 | help="Delimiter (only applicable to CSV files) [default: ',']") 26 | @click.option("--quotechar", "-q", type=str, default='"', 27 | help="Quote character (only applicable to CSV files) [default: '\"']") 28 | @click.option("--encoding", "-e", type=str, default="utf-8", 29 | help="Encoding [default: UTF-8]") 30 | @click.version_option(version=__version__) 31 | @click.argument('filename') 32 | def cli(filename, heading, file_type, delimiter, quotechar, encoding): 33 | """Display Excel or CSV files directly on your terminal. 34 | The file type is guessed from file extensions, but can be overridden with the --file-type option. 35 | """ 36 | if file_type is None: 37 | if filename.endswith(".csv"): 38 | file_type = "csv" 39 | else: 40 | file_type = "excel" 41 | 42 | if file_type == "csv": 43 | 44 | csv_rows = [] 45 | 46 | if not PY3: 47 | delimiter = str(unicode(delimiter)) 48 | quotechar = str(unicode(quotechar)) 49 | 50 | with open_file(filename, encoding) as f: 51 | reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar) 52 | for row in reader: 53 | csv_rows.append(row) 54 | 55 | cursor = CSVCursor(csv_rows, heading) 56 | 57 | else: 58 | # As per https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966 59 | # encodings in Excel are usually UTF-8. So, we only override the encoding 60 | # if an encoding is specified by the user. 61 | try: 62 | if encoding.lower() != "utf-8": 63 | workbook = xlrd.open_workbook(filename, encoding_override=encoding) 64 | else: 65 | workbook = xlrd.open_workbook(filename) 66 | except Exception as e: 67 | sys.exit(e) 68 | 69 | sheet = workbook.sheet_by_index(0) 70 | 71 | cursor = XCursor(sheet, heading) 72 | 73 | with out_proc() as out: 74 | 75 | asciitable.draw(cursor, out=out) 76 | 77 | --------------------------------------------------------------------------------