import argparse
import os
import shutil
import sys
rootPath = “/home/patrick/Sources/Segments/”
# set up command line argument parser
parser = argparse.ArgumentParser(prog=’segments’)
parser.add_argument(‘-l’, ‘–listfile’)
parser.add_argument(‘-b’, ‘–base’)
parser.add_argument(‘-r’, ‘–right’)
parser.add_argument(‘-d’, ‘–down’)
parser.add_argument(‘-c’, ‘–counter’, type=int, default=4)
parser.add_argument(‘-p’, ‘–pixelsize’, type=float, default=0.1)
# check first for list file and handle if found otherwise assume single line input
argList = sys.argv[1:] # drop the script name parameter
args = parser.parse_args(argList)
if args.listfile == None: # single line input from command line
listData = [” “.join(argList)]
else: # multi line input from file
listDataFileName = rootPath + args.listfile
listDataFile = open(listDataFileName, “r”)
listData = listDataFile.readlines()
listDataFile.close()
for listLine in listData:
# parse arguments
listLine = listLine.strip(“n”)
listItems = listLine.split(” “)
args = parser.parse_args(listItems)
#save the parameters
baseName = args.base
rightName = args.right
downName = args.down
counter = args.counter
pixelSize = args.pixelsize
- import sys is needed in order to use sys.argv which is the parameters typed on a command line.
- parser.add_argument calls are different. -b -d and -r are no longer mandatory and we put a new one in which is -l for the listfile.
- The next block is to parse the arguments to look for the list file parameter (-l). This time instead of using the default to parse_args which gets sys.argv itself, I have saved this into a string. We used sys.argv[1:] in order to drop the script name which is actually passed in as the first parameter; parse_args itself uses the same syntax to achieve the same thing.
- If a list file name was passed in then we read the list file into a list of strings. Each string contains one set of parameters. Otherwise we create a list containing one set of parameters from the command line. This means we have to first turn the command line parameter list into a string, with spaces between each parameter, and then turn that string into a list, which in this case will only have one string in it.
- We then enter a loop which loops through our list of parameter lines. We get each list item into a string.
- The first thing is to strip any newline characters (which is what we get as part of the input when we use readlines() to read multiple lines from a file, there will be a newline at the end of each line).
- Next is to split the string into a list whose items are the parameters themselves, using the split function with a space as input.
- Then finally we can call parse_args with this list as input.
From there the rest of the script is the same as before.