Improve command line arguments handling
This commit is contained in:
parent
0c21efc760
commit
2abb74f651
1 changed files with 10 additions and 32 deletions
42
SSnR.py
42
SSnR.py
|
@ -23,45 +23,26 @@
|
|||
#
|
||||
|
||||
import sys
|
||||
import getopt
|
||||
import argparse
|
||||
import regex
|
||||
|
||||
def main(args):
|
||||
def main():
|
||||
"""
|
||||
Main function
|
||||
:param args: Main arguments
|
||||
"""
|
||||
try:
|
||||
opts, args = getopt.getopt(args, "hr:s:", ["regex=", "string=", "help"])
|
||||
except getopt.GetoptError as err:
|
||||
print(err)
|
||||
print_help()
|
||||
return 2
|
||||
parser = argparse.ArgumentParser(description='Search and replace tool', prog='SSnR')
|
||||
parser.add_argument('-r', '--regex', help='Regex', required=True)
|
||||
parser.add_argument('-s', '--string', help='String', required=True)
|
||||
args = vars(parser.parse_args())
|
||||
|
||||
string = ""
|
||||
ex = ""
|
||||
|
||||
for opt, arg in opts:
|
||||
if opt in ("-h", "--help"):
|
||||
print_help()
|
||||
return 0
|
||||
elif opt in ("-r", "--regex"):
|
||||
ex = arg
|
||||
elif opt in ("-s", "--string"):
|
||||
string = arg
|
||||
|
||||
if (string == "") or (ex == ""):
|
||||
print_help()
|
||||
return -2
|
||||
|
||||
search(ex, string)
|
||||
search(args["regex"], args["string"])
|
||||
return 0
|
||||
|
||||
def search(ex, string):
|
||||
"""
|
||||
Search in a string
|
||||
:param ex: regular expression
|
||||
:param string: a string
|
||||
:param ex: Regular expression
|
||||
:param string: A string
|
||||
"""
|
||||
regex_compile = regex.compile(ex, regex.MULTILINE)
|
||||
if regex_compile is None:
|
||||
|
@ -74,9 +55,6 @@ def search(ex, string):
|
|||
":" + str(match.end(0)) + "]")
|
||||
print("Number of match: " + str(nb_match))
|
||||
|
||||
def print_help():
|
||||
print('SSnR.py -s <string> -r <regex>')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
sys.exit(main())
|
||||
|
|
Loading…
Reference in a new issue