From 897abc011d161bbb285e7d7c0cea4c2bf934ece4 Mon Sep 17 00:00:00 2001 From: Oleg Broytman Date: Sat, 3 Sep 2016 00:16:02 +0300 Subject: [PATCH] Change arguments handling Allow `-` to name stdin or stdout. Input file is always the first argument, no need to use option `-i`. Output file can be named with `-o` or as the second argument but not both. Option `-o` is useful when there is no input file (input is redirected, for example: `mysql-to-sql.py -o out.sql < in.sql`). --- docs/index.rst | 17 ++++++++++++++--- scripts/mysql-to-sql.py | 37 ++++++++++++++++++++++++++++--------- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index e9c3631..356f1d1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -25,12 +25,23 @@ mysql-to-sql.py Usage:: - mysql-to-sql.py [-i infile] [-o outfile] + mysql-to-sql.py [infile] [[-o] outfile] Options:: - -i, --infile infile Input file, stdin if absent - -o, --outfile outfile Output file, stdout if absent + infile Input file, stdin if absent or '-' + -o, --outfile outfile Output file, stdout if absent or '-' + +Option `-o` is useful when infile is absent (input is redirected), for +example:: + + mysql-to-sql.py -o outfile.sql < infile.sql + cat infile.sql | mysql-to-sql.py -o outfile.sql + +But of course it simple can be:: + + mysql-to-sql.py - outfile.sql < infile.sql + cat infile.sql | mysql-to-sql.py - outfile.sql Indices and tables diff --git a/scripts/mysql-to-sql.py b/scripts/mysql-to-sql.py index be137a8..c40563f 100755 --- a/scripts/mysql-to-sql.py +++ b/scripts/mysql-to-sql.py @@ -24,27 +24,46 @@ def main(infile, outfile): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert MySQL to SQL') - parser.add_argument('-i', '--infile', help='input file name') parser.add_argument('-o', '--outfile', help='output file name') + parser.add_argument('infile', help='input file name') + parser.add_argument('output_file', nargs='?', help='output file name') args = parser.parse_args() if args.infile: - infile = open(args.infile, 'rt') + if args.infile == '-': + infile = sys.stdin + else: + infile = open(args.infile, 'rt') else: infile = sys.stdin - if infile.isatty(): - print("Error: cannot input from console", file=sys.stderr) - parser.print_help() - sys.exit() + + if infile.isatty(): + print("Error: cannot read from console", file=sys.stderr) + parser.print_help() + sys.exit(1) if args.outfile: + if args.output_file: + print("Error: too many output files", file=sys.stderr) + parser.print_help() + sys.exit(1) + + outfile = args.outfile + + elif args.output_file: + outfile = args.output_file + + else: + outfile = '-' + + if outfile == '-': + outfile = sys.stdout + else: try: - outfile = open(args.outfile, 'wt') + outfile = open(outfile, 'wt') except: if infile is not sys.stdin: infile.close() raise - else: - outfile = sys.stdout main(infile, outfile) -- 2.39.2