Debian Codegraph @

clevercsv/console/commands/explore.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 import code
4 import sys
5
6 from wilderness import Command
7
8 from clevercsv.encoding import get_encoding
9 from clevercsv.wrappers import detect_dialect
10
11 from ._docs import FLAG_DESCRIPTIONS
12 from ._utils import generate_code
13 from ._utils import parse_int
14
15
16 class ExploreCommand(Command):
17 _description = (
18 "The explore command allows you to quickly explore a CSV file in an "
19 "interactive Python shell. This command detects the dialect of the "
20 "CSV file and drops you into a Python interactive shell (REPL), "
21 "with the CSV file already loaded. Simply run:\n\n"
22 "\tclevercsv explore FILE\n\n"
23 "to start working with the file loaded as a list of lists. "
24 "Alternatively, you can run:\n\n"
25 "\tclevercsv explore -p FILE\n\n"
26 "to read the file as a Pandas dataframe."
27 )
28
29 def __init__(self) -> None:
30 super().__init__(
31 name="explore",
32 title="Explore the CSV file in an interactive Python shell",
33 description=self._description,
34 extra_sections={"CleverCSV": "Part of the CleverCSV suite"},
35 )
36
37 def register(self) -> None:
38 self.add_argument("path", help="Path to the CSV file")
39 self.add_argument(
40 "-e",
41 "--encoding",
42 help="Set the encoding of the file",
43 description=FLAG_DESCRIPTIONS["encoding"],
44 )
45 self.add_argument(
46 "-n",
47 "--num-chars",
48 help="Number of characters to use for detection",
49 type=int,
50 description=FLAG_DESCRIPTIONS["num-chars"],
51 )
52 self.add_argument(
53 "-p",
54 "--pandas",
55 action="store_true",
56 help="Read the file into a Pandas DataFrame",
57 description=(
58 "By default, this command imports the CSV file as a list of "
59 "lists. By enabling this option the script will be written "
60 "such that the file will be read as a Pandas DataFrame "
61 "instead."
62 ),
63 )
64
65 def handle(self) -> int:
66 filename = self.args.path
67 encoding = self.args.encoding or get_encoding(filename)
68 num_chars = parse_int(self.args.num_chars, "num-chars")
69 dialect = detect_dialect(
70 filename,
71 num_chars=num_chars,
72 encoding=encoding,
73 verbose=self.args.verbose,
74 )
75 if dialect is None:
76 print("Error: dialect detection failed.", file=sys.stderr)
77 return 1
78
79 code_lines = generate_code(
80 filename, dialect, encoding, use_pandas=self.args.pandas
81 )
82
83 console = code.InteractiveConsole()
84 for line in code_lines:
85 retcode = console.push(line)
86 if retcode:
87 print(
88 "An error occurred starting the interactive console. "
89 "Printing commands instead:\n"
90 )
91 print("\n".join(code_lines))
92 return 1
93
94 print("Dropping you into an interactive shell.\n")
95 banner = "CleverCSV has loaded the data into the variable: "
96 banner += "df" if self.args.pandas else "rows"
97 console.interact(banner=banner)
98 return 0