How to use parse_cmdln_args method in rester

Best Python code snippet using rester_python

continuum_removal.py

Source:continuum_removal.py Github

copy

Full Screen

...30__license__ = 'GPLv3'31__maintainer = 'Carey Legett'32__status__ = 'Development'33__version__ = '1.0'34def parse_cmdln_args():35 """A function to parse command line arguments for this module.36 37 This function is used when this module is run as a script to parse38 commandline arguments into the appropriate variables. It also provides39 useage help information when run with the -h flag.40 41 Example:42 To invoke the help text and get information about the proper command43 line flags, run the script with the -h or --help flags.44 $ python3 continuum_removal.py -h45 or46 $ python3 continuum_removal.py --help47 48 Returns:49 args (argparse.Namespace): An object containing the state of the50 variables set via command line options. Individual elements are51 accessible with standard `args.element`_ notation.52 53 """54 parser = argparse.ArgumentParser(prog='continuum_removal.py',55 description=__doc__,56 epilog='''For more information contact 57 Chip at carey.legett@stonybrook.edu.''')58 parser.add_argument('-f', '--input-file', required=True,59 help='''The name of the input file (include path if the60 file is not in this directory).''', dest='ifile')61 parser.add_argument('-a', '--xstart', type=int, required=True,62 help='''The x value at which to begin the continuum 63 calculation.''', dest='xa')64 parser.add_argument('-b', '--xstop', type=int, required=True, help='''The x65 value at which to end the continuum calculation.''',66 dest='xb')67 group = parser.add_mutually_exclusive_group(required=True)68 group.add_argument('-d', '--delimiter', help='''The delimiter for the input69 file. A single character representing the actual 70 delimiter. Mutually exclusive with -w or 71 --whitespace''', dest='delim')72 group.add_argument('-w', '--whitespace', help='''Indicates the delimiter is73 either tabs or spaces. Mutually exclusive with -d or 74 --delimiter.''', action='store_true', dest='whitespace')75 parser.add_argument('-n', '--skip-lines', default=0, help='''Skip this many76 lines of the input file before reading in data.''',77 type=int, dest='skip')78 parser.add_argument('-o', '--output-file', nargs='?', default='output.txt', 79 help='''The name of the output file (include path 80 if you want the file somewhere other than in the 81 current directory). Defaults to output.txt.''',82 dest='ofile')83 parser.add_argument('-i', '--include-input', action='store_true', dest='i',84 help='''Write the original input data before the85 (optional) continuum fit and continuum removed 86 data.''')87 parser.add_argument('-c', '--continuum-output', action='store_true',88 dest='c', help='''Write the continuum fit for each 89 input x value after the (optional) original input data 90 and before the continuum removed data.''')91 parser.add_argument('-v', '--verbose', action='store_true', dest='v', 92 help='Give status information during processing.')93 94 return parser.parse_args()95def read_input_file(input_filename, input_delimiter, whitespace_flag, 96 lines_to_skip, verbose_flag):97 """Reads the specified input file and returns a list of the data therein.98 This function reads an input file using a specified delimiter, skipping a99 given number of lines before reading. It also accepts a verbosity flag to100 enable some progress text while reading.101 Args:102 input_filename (str): The file to be read103 input_delimiter (str): The delimiter used in the input file. Set this104 to `None` if the delimiter is some form of whitespace. 105 whitespace_flag (bool): True if the delimiter is some form of106 whitespace, False otherwise. Must be false if `input_delimiter` is107 not `None`.108 lines_to_skip (int): The number of lines to skip at the beginning of109 the file before ingesting data. 110 verbose_flag (bool): True for progress output, False otherwise.111 Returns:112 data ([float,float]): A list of lists of floats containing the data113 read in from the input file.114 Raises:115 IOError: if there is a problem opening or reading the input file116 ValueError: if the data that is read from the file cannot be converted117 to a float. (e.g. the read data is not numeric)118 """119 if verbose_flag:120 print('Reading input file...')121 # Check for the version of python being used and use appropriate flags for122 # opening the input file as necessary123 if sys.version_info[0] == 2:124 raccess = 'rb'125 kwargs = {}126 else:127 raccess = 'rt'128 kwargs = {'newline': ''}129 130 try:131 with open(input_filename, raccess, **kwargs) as infile:132 if whitespace_flag:133 rawdata = [line.split() for line in itertools.islice(infile,134 lines_to_skip, None)]135 else:136 rawdata = [line.split(input_delimiter) for line in137 itertools.islice(infile, lines_to_skip, None)]138 if not rawdata:139 sys.exit('No data in file {}'.format(input_filename))140 except IOError as e:141 sys.exit('I/O error: file {}: {}'.format(input_filename, e))142 mydata = [[float(astring) for astring in inner] for inner in rawdata]143 # If this fails, it is likely that the data read from the input file is not144 # numeric. It could also happen if the delimiter was not correctly145 # specified.146 return mydata147def remove_continuum(mydata, xa, xb, verbose_flag):148 """A function to remove the linear continuum between two points.149 150 This function takes a list of lists of floats containing x,y data, a151 starting x value, and an ending x value and calculates a linear fit to the152 data at those two points, extrapolated over the provided domain of x. The153 data is then normalized such that the calculated continuum equals 1. This154 can be used to prepare data for analyses such as measuring the band depth155 of absorptions in spectroscopic data.156 157 Args:158 mydata ([float, float]): A list of lists of two floats representing the159 unnormalized initial data.160 xa (float): The value of x at which to start the linear fit. This161 must be an x value in the range of the data list since the162 searching doesn't check to make sure xa falls within the bounds of163 the data.164 xb (float): The value of x at which to stop the linear fit. This165 must be an x value in the range of the data list since the166 searching doesn't check to make sure xa falls within the bounds of167 the data.168 verbose_flag (bool): True for progress output, False otherwise.169 170 Returns:171 output ([float, float]): A list of lists of two to four floats. The172 first element in each inner list will be the input x value. The 173 second element will be the input y value. The third element will 174 be the continuum value calculated for that x. The last element 175 will be the continuum-removed y data.176 177 """178 if verbose_flag:179 print('Calculating continuum line')180 start_index = np.abs(np.array(mydata)[:, 0] - xa).argmin()181 stop_index = np.abs(np.array(mydata)[:, 0] - xb).argmin()182 startx = mydata[start_index][0]183 stopx = mydata[stop_index][0]184 starty = mydata[start_index][1]185 stopy = mydata[stop_index][1]186 187 if verbose_flag: 188 print('Start: ({!s},{!s})'.format(startx, starty))189 print('Stop: ({!s},{!s})'.format(stopx, stopy))190 191 slope = (stopy-starty)/(stopx-startx)192 intercept = starty-(slope*startx)193 194 if verbose_flag:195 print('Continuum equation: y={}*x+{}'.format(slope, intercept))196 print('Removing continuum')197 198 this_output = []199 for element in mydata:200 continuum = slope*element[0]+intercept201 crdata = element[1]/continuum202 temp_output = [element[0], element[1], continuum, crdata]203 this_output.append(temp_output)204 return this_output205def write_cont_removed_output(myoutput, output_filename, write_input_flag,206 write_cont_flag, verbose_flag):207 """A function to write the provided list of lists of floats to a CSV file.208 209 This function writes the continuum removed data to a CSV file. Depending on210 the arguments passed, it may also write the original input data, and the211 calculated continuum for each x value.212 213 Args:214 myoutput ([float, float, float, float]): A list of lists of four floats215 that will be written, in part or in whole to the output file.216 output_filename (str): The name of the output file.217 write_input_flag (bool): True if we want to include the original data218 in the output file, False otherwise.219 write_cont_flag (bool): True if we want to include the value of the220 continuum at each x value in the output file, False otherwise.221 verbose_flag (bool): True for progress message, False otherwise.222 223 Raises:224 IOError: For any problem opening or writing to the output file.225 226 Output:227 A CSV file containing two to four columns of data as selected with the228 arguments passed to the function.229"""230 if verbose_flag:231 print('Writing output file')232 # Check for the version of python being used and use appropriate flags for233 # opening the input file as necessary234 if sys.version_info[0] == 2:235 waccess = 'wb'236 kwargs = {}237 else:238 waccess = 'w'239 kwargs = {'newline': ''}240 try:241 with open(output_filename, waccess, **kwargs) as outfile:242 writer = csv.writer(outfile)243 header = ['x']244 filtered_output = []245 for line in myoutput:246 temp = [line[0]]247 if write_input_flag:248 temp.append(line[1])249 if write_cont_flag:250 temp.append(line[2])251 temp.append(line[3])252 filtered_output.append(temp)253 if write_input_flag:254 header.append('original')255 if write_cont_flag:256 header.append('continuum')257 header.append(f'cont_removed{output_filename}')258 writer.writerow(header)259 writer.writerows(filtered_output)260 except IOError as e:261 sys.exit('Output file error: {}, {}'.format(e, sys.exc_info()))262if __name__ == '__main__':263 args = parse_cmdln_args()264 data = read_input_file(args.ifile, args.delim, args.whitespace, args.skip,265 args.v)266 output = remove_continuum(data, float(args.xa), float(args.xb), args.v)...

Full Screen

Full Screen

wl_to_wn.py

Source:wl_to_wn.py Github

copy

Full Screen

...29__maintainer = 'Carey Legett'30__status__ = 'Development'31__version__ = '0.1a'32ureg = UnitRegistry()33def parse_cmdln_args():34 """A function to parse command line arguments for this module.35 This function is used when this module is run as a script to parse36 commandline arguments into the appropriate variables. It also provides37 useage help information when run with the -h flag.38 Example:39 To invoke the help text and get information about the proper command40 line flags, run the script with the -h or --help flags.41 $ python3 continuum_removal.py -h42 or43 $ python3 continuum_removal.py --help44 Returns:45 args (argparse.Namespace): An object containing the state of the46 variables set via command line options. Individual elements are47 accessible with standard `args.element`_ notation.48 """49 parser = argparse.ArgumentParser(prog='wl_to_wn.py',50 description=__doc__,51 epilog='''For more information contact 52 Chip at carey.legett@stonybrook.edu.''')53 parser.add_argument('-f', '--input-file', required=True,54 help='''The name of the input file (include path if the55 file is not in this directory).''', dest='ifile')56 parser.add_argument('-x', '--xunits', type=str, required=True,57 help='''The units that the x data are in (e.g. 58 'micrometers' or 'wavenumbers'.''', dest='xunits')59 group = parser.add_mutually_exclusive_group(required=True)60 group.add_argument('-d', '--delimiter', help='''The delimiter for the input61 file. A single character representing the actual 62 delimiter. Mutually exclusive with -w or 63 --whitespace''', dest='in_delim')64 group.add_argument('-w', '--whitespace', help='''Indicates the delimiter is65 either tabs or spaces. Mutually exclusive with -d or 66 --delimiter.''', action='store_true', dest='whitespace')67 parser.add_argument('-n', '--skip-lines', default=0, help='''Skip this many68 lines of the input file before reading in data.''',69 type=int, dest='skip')70 parser.add_argument('-o', '--output-file', nargs='?', default='output.txt',71 help='''The name of the output file (include path 72 if you want the file somewhere other than in the 73 current directory). Defaults to output.txt.''',74 dest='ofile')75 parser.add_argument('-s', '--output-delimiter', required=False, help='''The76 delimiter to be used in the output file. Defults to tab77 .''', dest='out_delim')78 parser.add_argument('-v', '--verbose', action='store_true', dest='v',79 help='Give status information during processing.')80 return parser.parse_args()81def read_input_file(filename, delimiter, whitespace_flag, skip_lines, xunits,82 verbose):83 if verbose:84 print('Reading input file...')85 try:86 with open(filename, 'rt', newline='') as infile:87 if whitespace_flag:88 rawdata = [line.split() for line in89 itertools.islice(infile, skip_lines, None)]90 else:91 rawdata = [line.split(delimiter) for line in92 itertools.islice(infile, skip_lines, None)]93 if not rawdata:94 sys.exit('No data in file {}'.format(filename))95 except IOError as e:96 sys.exit('I/O error: file {}: {}'.format(filename, e))97 mydata = [[float(astring) for astring in inner] for inner in rawdata]98 if verbose:99 print('Assigning units.')100 mydata = [[row[0] * ureg[f'{xunits}'], row[1]] for row in mydata]101 # If this fails, it is likely that the data read from the input file is not102 # numeric. It could also happen if the delimiter was not correctly103 # specified.104 if verbose:105 print('Done with input.')106 return mydata107def write_to_output(somedata, out_filename, out_delim, verbose_flag):108 if verbose_flag:109 print('Writing output file')110 try:111 with open(out_filename, 'w', newline='') as outfile:112 writer = csv.writer(outfile, delimiter=out_delim)113 header = ['wn', 'data']114 writer.writerow(header)115 writer.writerows(somedata)116 except IOError as e:117 sys.exit(f'Output file error: {e}, {sys.exc_info()}')118if __name__ == '__main__':119 args = parse_cmdln_args()120 x = ureg[f'{args.xunits}']121 data = read_input_file(args.ifile, args.in_delim, args.whitespace,122 args.skip, args.xunits, args.v)123 data = [[line[0].to(1 / ureg.centimeter, 'sp').magnitude, line[1]] for line in data]...

Full Screen

Full Screen

apirunner.py

Source:apirunner.py Github

copy

Full Screen

2import argparse3import logging4import sys5DEFAULT_TEST_CASE = 'test_case.json'6def parse_cmdln_args():7 parser = argparse.ArgumentParser(description='Process command line args')8 parser.add_argument('--log', help='log help', default='INFO')9 parser.add_argument(10 '--tc', help='tc help')11 parser.add_argument(12 '--ts', help='ts help')13 args = parser.parse_args()14 return (args.log.upper(), args.tc, args.ts)15def run():16 log_level, test_case_file, test_suite_file = parse_cmdln_args()17 print log_level, test_case_file, test_suite_file18 logging.basicConfig()19 logger = logging.getLogger('rester')20 logger.setLevel(log_level)21 test_runner = ApiTestCaseRunner()22 if test_case_file is not None:23 print "test case has been specified"24 test_runner.run_test_case(test_case_file)25 elif test_suite_file is not None:26 print "test suite has been specified"27 test_runner.run_test_suite(test_suite_file)28 else:29 print "running the default test case"30 test_runner.run_test_case(DEFAULT_TEST_CASE)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run rester automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful