Skip to content

Commit 5fb5f71

Browse files
ran black
1 parent c519481 commit 5fb5f71

3 files changed

Lines changed: 123 additions & 43 deletions

File tree

cs_util/args.py

Lines changed: 94 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""ARGS
1+
"""ARGS.
22
33
:Description: Handling of command line arguments.
44
@@ -7,8 +7,11 @@
77
88
"""
99

10+
import sys
11+
from optparse import OptionParser
1012

11-
def parse_options(p_def, short_options, types, help_strings):
13+
14+
def parse_options(p_def, short_options, types, help_strings, args=None):
1215
"""Parse command line options.
1316
1417
Parameters
@@ -26,45 +29,46 @@ def parse_options(p_def, short_options, types, help_strings):
2629
-------
2730
options: tuple
2831
Command line options
32+
2933
"""
34+
if args is None:
35+
args = sys.argv[1:]
3036

31-
usage = "%prog [OPTIONS]"
37+
usage = "%prog [OPTIONS]"
3238
parser = OptionParser(usage=usage)
3339

3440
# Loop over default parameter values
3541
for key in p_def:
36-
3742
# Process if help string exists
3843
if key in help_strings:
39-
4044
# Set short option
4145
if key in short_options:
4246
short = short_options[key]
4347
else:
4448
# Default is no short option
45-
short = ''
49+
short = ""
4650

4751
# Set type
4852
if key in types:
4953
typ = types[key]
5054
else:
5155
# Default is str
52-
typ = 'string'
56+
typ = "string"
5357

5458
# Special case: bool type
55-
if typ == 'bool':
59+
if typ == "bool":
5660
parser.add_option(
57-
f'{short}',
58-
f'--{key}',
61+
f"{short}",
62+
f"--{key}",
5963
dest=key,
6064
default=False,
61-
action='store_true',
65+
action="store_true",
6266
help=help_strings[key].format(p_def[key]),
6367
)
6468
else:
6569
parser.add_option(
6670
short,
67-
f'--{key}',
71+
f"--{key}",
6872
dest=key,
6973
type=typ,
7074
default=p_def[key],
@@ -73,13 +77,85 @@ def parse_options(p_def, short_options, types, help_strings):
7377

7478
# Add verbose option
7579
parser.add_option(
76-
'-v',
77-
'--verbose',
78-
dest='verbose',
79-
action='store_true',
80-
help=f'verbose output'
80+
"-v",
81+
"--verbose",
82+
dest="verbose",
83+
action="store_true",
84+
help=f"verbose output",
8185
)
8286

83-
options, args = parser.parse_args()
87+
options, my_args = parser.parse_args(args)
8488

8589
return options
90+
91+
92+
def my_string_split(string, num=-1, verbose=False, stop=False, sep=None):
93+
"""My String Split.
94+
95+
Split a *string* into a list of strings. Choose as separator
96+
the first in the list [space, underscore] that occurs in the string.
97+
(Thus, if both occur, use space.)
98+
99+
Parameters
100+
----------
101+
string : str
102+
Input string
103+
num : int
104+
Required length of output list of strings, -1 if no requirement.
105+
verbose : bool
106+
Verbose output
107+
stop : bool
108+
Stop programs with error if True, return None and continues otherwise
109+
sep : bool
110+
Separator, try ' ', '_', and '.' if None (default)
111+
112+
Raises
113+
------
114+
ValueError
115+
If number of elements in string and num are different, for stop=True
116+
If no separator found in string
117+
118+
Returns
119+
-------
120+
list
121+
List of string on success, and None if failed
122+
123+
"""
124+
if string is None:
125+
return None
126+
127+
if sep is None:
128+
has_space = string.find(" ")
129+
has_underscore = string.find("_")
130+
has_dot = string.find(".")
131+
132+
if has_space != -1:
133+
my_sep = " "
134+
elif has_underscore != -1:
135+
my_sep = "_"
136+
elif has_dot != -1:
137+
my_sep = "."
138+
else:
139+
# no separator found, does string consist of only one element?
140+
if num == -1 or num == 1:
141+
my_sep = None
142+
else:
143+
raise ValueError(
144+
"No separator (' ', '_', or '.') found in string"
145+
+ f" '{string}', cannot split"
146+
)
147+
else:
148+
if not string.find(sep):
149+
raise ValueError(
150+
f"No separator '{sep}' found in string '{string}' cannot split"
151+
)
152+
my_sep = sep
153+
154+
res = string.split(my_sep)
155+
156+
if num != -1 and num != len(res) and stop:
157+
raise ValueError(
158+
f"String '{len(res)}' has length {num}, required is {num}"
159+
)
160+
161+
return res

cs_util/plots.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ def savefig(fname, close_fig=True):
5353

5454

5555
def dx(idx, nx=3, fx=1.025, log=True):
56-
"""Dx Plot.
56+
"""Dx.
57+
5758
Return small shift useful to diplace points along the the x-axis
5859
for a more readable plot.
5960
@@ -74,6 +75,7 @@ def dx(idx, nx=3, fx=1.025, log=True):
7475
else:
7576
return fx * (idx - (nx - 1) / 2)
7677

78+
7779
def plot_histograms(
7880
xs,
7981
labels,
@@ -261,7 +263,7 @@ def plot_data_1d(
261263
if linewidths is None:
262264
linewidths = [2] * len(x)
263265
if markers is None:
264-
markers = ['o'] * len(x)
266+
markers = ["o"] * len(x)
265267

266268
if create_figure:
267269
figure(figsize=(10, 10))
@@ -292,7 +294,7 @@ def plot_data_1d(
292294
)
293295
eb[-1][0].set_linestyle(eb_linestyles[idx])
294296

295-
plt.axhline(color="k", linestyle="dashed", linewidth=linewidths[0]/2)
297+
plt.axhline(color="k", linestyle="dashed", linewidth=linewidths[0] / 2)
296298

297299
if xlog:
298300
plt.xscale("log")

cs_util/tests/test_args.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,51 +13,53 @@
1313

1414
from cs_util import args
1515

16+
1617
class ArgsTestCase(TestCase):
1718
"""Test case for the ``args`` module."""
1819

1920
def setUp(self):
2021
"""Set test parameter values."""
2122
self._params_def = {
22-
"p_int" : 1,
23-
"p_float" : 0.612,
24-
"p_bool" : True,
25-
"p_str" : "some_string",
26-
"p_str_def" : "second_string",
27-
"p_none" : "",
23+
"p_int": 1,
24+
"p_float": 0.612,
25+
"p_bool": True,
26+
"p_str": "some_string",
27+
"p_str_def": "second_string",
28+
"p_none": "",
2829
}
2930
self._types = {
30-
"p_int" : "int",
31-
"p_float" : "float",
32-
"p_bool" : "bool",
33-
"p_str" : "str",
31+
"p_int": "int",
32+
"p_float": "float",
33+
"p_bool": "bool",
34+
"p_str": "str",
3435
}
3536
self._short_options = {
36-
"p_int" : "-i",
37-
"p_float" : "-f",
38-
"p_bool" : "-b",
39-
"p_str" : "-s",
37+
"p_int": "-i",
38+
"p_float": "-f",
39+
"p_bool": "-b",
40+
"p_str": "-s",
4041
}
4142
self._help_strings = {
42-
"p_int" : "integer option, default={}",
43-
"p_float" : "float option, default={}",
44-
"p_bool" : "bool option, default={}",
45-
"p_str" : "string option, default={}".
43+
"p_int": "integer option, default={}",
44+
"p_float": "float option, default={}",
45+
"p_bool": "bool option, default={}",
46+
"p_str": "string option, default={}",
4647
}
4748

4849
def tearDown(self):
4950
"""Unset test parameter values."""
5051
self._params_def = None
5152
self._types = None
52-
self._short_options = None
53+
5354
self._help_strings = None
5455

5556
def test_parse_options(self):
5657
"""Test `cs_util.args.parse_options` method."""
57-
options = args.parse_options(
58+
self._options = args.parse_options(
5859
self._params_def,
5960
self._short_options,
6061
self._types,
61-
self._help_strings
62+
self._help_strings,
63+
args=["-i", "2", "-s", "test"],
6264
)
63-
print(options)
65+
print(self._options)

0 commit comments

Comments
 (0)