| 1 |
|
| 2 |
|
| 3 |
import sys |
| 4 |
|
| 5 |
from wilderness import Command |
| 6 |
|
| 7 |
from clevercsv.encoding import get_encoding |
| 8 |
from clevercsv.wrappers import detect_dialect |
| 9 |
|
| 10 |
from ._docs import FLAG_DESCRIPTIONS |
| 11 |
from ._utils import generate_code |
| 12 |
from ._utils import parse_int |
| 13 |
|
| 14 |
|
| 15 |
class CodeCommand(Command): |
| 16 |
_description = ( |
| 17 |
"Generate Python code for importing a given CSV file. This is " |
| 18 |
"especially useful if you don't want to repeatedly detect the dialect " |
| 19 |
"of the same file. Simply run:\n\n" |
| 20 |
"\tclevercsv code your_csv_file.csv\n\n" |
| 21 |
"and copy the generated code to a Python script." |
| 22 |
) |
| 23 |
|
| 24 |
def __init__(self) -> None: |
| 25 |
super().__init__( |
| 26 |
name="code", |
| 27 |
title="Generate Python code to import a CSV file", |
| 28 |
description=self._description, |
| 29 |
extra_sections={"CleverCSV": "Part of the CleverCSV suite"}, |
| 30 |
) |
| 31 |
|
| 32 |
def register(self) -> None: |
| 33 |
self.add_argument("path", help="Path to the CSV file") |
| 34 |
self.add_argument( |
| 35 |
"-e", |
| 36 |
"--encoding", |
| 37 |
help="Set the encoding of the file", |
| 38 |
description=FLAG_DESCRIPTIONS["encoding"], |
| 39 |
) |
| 40 |
self.add_argument( |
| 41 |
"-n", |
| 42 |
"--num-chars", |
| 43 |
type=int, |
| 44 |
help="Number of characters to use for detection", |
| 45 |
description=FLAG_DESCRIPTIONS["num-chars"], |
| 46 |
) |
| 47 |
self.add_argument( |
| 48 |
"-p", |
| 49 |
"--pandas", |
| 50 |
action="store_true", |
| 51 |
help="Write code that uses a Pandas DataFrame", |
| 52 |
description=( |
| 53 |
"By default, this command writes a small Python script to " |
| 54 |
"import the CSV file as a list of lists. By enabling this " |
| 55 |
"option the script will be written such that the file will be " |
| 56 |
"read as a Pandas DataFrame instead." |
| 57 |
), |
| 58 |
) |
| 59 |
|
| 60 |
def handle(self) -> int: |
| 61 |
filename = self.args.path |
| 62 |
encoding = self.args.encoding or get_encoding(filename) |
| 63 |
num_chars = parse_int(self.args.num_chars, "num-chars") |
| 64 |
dialect = detect_dialect( |
| 65 |
filename, |
| 66 |
num_chars=num_chars, |
| 67 |
encoding=encoding, |
| 68 |
verbose=self.args.verbose, |
| 69 |
) |
| 70 |
if dialect is None: |
| 71 |
print("Error: dialect detection failed.", file=sys.stderr) |
| 72 |
return 1 |
| 73 |
|
| 74 |
code_lines = generate_code( |
| 75 |
filename, dialect, encoding, use_pandas=self.args.pandas |
| 76 |
) |
| 77 |
print("\n".join(code_lines)) |
| 78 |
return 0 |