Improve command line arguments handling

This commit is contained in:
Rémi BERTHO 2017-10-08 18:25:04 +02:00
parent 0c21efc760
commit 2abb74f651
Signed by: dalan
GPG Key ID: EE3B917931C07B64
1 changed files with 10 additions and 32 deletions

42
SSnR.py
View File

@ -23,45 +23,26 @@
# #
import sys import sys
import getopt import argparse
import regex import regex
def main(args): def main():
""" """
Main function Main function
:param args: Main arguments
""" """
try: parser = argparse.ArgumentParser(description='Search and replace tool', prog='SSnR')
opts, args = getopt.getopt(args, "hr:s:", ["regex=", "string=", "help"]) parser.add_argument('-r', '--regex', help='Regex', required=True)
except getopt.GetoptError as err: parser.add_argument('-s', '--string', help='String', required=True)
print(err) args = vars(parser.parse_args())
print_help()
return 2
string = "" search(args["regex"], 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)
return 0 return 0
def search(ex, string): def search(ex, string):
""" """
Search in a string Search in a string
:param ex: regular expression :param ex: Regular expression
:param string: a string :param string: A string
""" """
regex_compile = regex.compile(ex, regex.MULTILINE) regex_compile = regex.compile(ex, regex.MULTILINE)
if regex_compile is None: if regex_compile is None:
@ -74,9 +55,6 @@ def search(ex, string):
":" + str(match.end(0)) + "]") ":" + str(match.end(0)) + "]")
print("Number of match: " + str(nb_match)) print("Number of match: " + str(nb_match))
def print_help():
print('SSnR.py -s <string> -r <regex>')
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main(sys.argv[1:])) sys.exit(main())