Skip to content

Commit ca5d91a

Browse files
committed
Added csv output format
1 parent 00e6a06 commit ca5d91a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

SoftLayer/CLI/core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
}
3535

3636
PROG_NAME = "slcli (SoftLayer Command-line)"
37-
VALID_FORMATS = ['table', 'raw', 'json', 'jsonraw']
37+
VALID_FORMATS = ['table', 'raw', 'json', 'jsonraw', 'csv']
3838
DEFAULT_FORMAT = 'raw'
3939

4040
if sys.stdout.isatty():

SoftLayer/CLI/formatting.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
"""
77
# pylint: disable=E0202, consider-merging-isinstance, arguments-differ, keyword-arg-before-vararg
88
import collections
9+
import csv
910
import json
1011
import os
12+
import tempfile
1113

1214
import click
1315
from rich import box
@@ -29,6 +31,8 @@ def format_output(data, fmt='table'): # pylint: disable=R0911,R0912
2931
return json.dumps(data, indent=4, cls=CLIJSONEncoder)
3032
elif fmt == 'jsonraw':
3133
return json.dumps(data, cls=CLIJSONEncoder)
34+
if fmt == 'csv':
35+
return csv_output_format(data)
3236

3337
if isinstance(data, str) or isinstance(data, rTable):
3438
return data
@@ -440,3 +444,29 @@ def _format_list_objects(result):
440444
table.add_row(values)
441445

442446
return table
447+
448+
449+
def csv_output_format(data, delimiter=','):
450+
"""Formating a table to csv format and show it."""
451+
data = clean_null_table_rows(data)
452+
with tempfile.TemporaryDirectory() as temp_file:
453+
f_name = os.path.join(temp_file, 'temp_csv_file')
454+
with open(f_name, 'w', encoding='UTF8') as file:
455+
writer = csv.writer(file, delimiter=delimiter)
456+
writer.writerow(data.columns)
457+
writer.writerows(data.rows)
458+
with open(f_name, 'r', encoding='UTF8') as file:
459+
csv_file = csv.reader(file, delimiter='\t')
460+
for row in csv_file:
461+
if len(row) != 0:
462+
print(row[0])
463+
return ''
464+
465+
466+
def clean_null_table_rows(data):
467+
"""Delete Null fields by '-', in a table"""
468+
for index_i, row in enumerate(data.rows):
469+
for index_j, value in enumerate(row):
470+
if str(value) + '' == 'NULL':
471+
data.rows[index_i][index_j] = '-'
472+
return data

0 commit comments

Comments
 (0)