fork download
  1. from __future__ import print_function
  2.  
  3. script = """
  4.  
  5. import argparse
  6. import sys
  7.  
  8. parser = argparse.ArgumentParser(prog='script', description="This is an example.",
  9. usage='%(prog)s [-h] (--file FILE | FILE)')
  10. group = parser.add_mutually_exclusive_group(required=True)
  11. group.add_argument('positional_file', nargs='?', help='specifies a file.')
  12. group.add_argument('--file', help='specifies a file.')
  13.  
  14. args = parser.parse_args()
  15. print(sys.argv[1:])
  16. print(args)
  17. file = args.positional_file if args.file is None else args.file
  18. """
  19.  
  20. import sys
  21. from subprocess import call
  22.  
  23. for args in (["abc"], ["--file", "abc"], ["--file", "abc", "def"], [],
  24. ['-h'], ['-h', '1'], ['--help']):
  25. print("run with {}".format(args), file=sys.stderr)
  26. call([sys.executable, "-c", script] + args)
Success #stdin #stdout #stderr 1.17s 10040KB
stdin
Standard input is empty
stdout
['abc']
Namespace(file=None, positional_file='abc')
['--file', 'abc']
Namespace(file='abc', positional_file=None)
usage: script [-h] (--file FILE | FILE)

This is an example.

positional arguments:
  positional_file  specifies a file.

optional arguments:
  -h, --help       show this help message and exit
  --file FILE      specifies a file.
usage: script [-h] (--file FILE | FILE)

This is an example.

positional arguments:
  positional_file  specifies a file.

optional arguments:
  -h, --help       show this help message and exit
  --file FILE      specifies a file.
usage: script [-h] (--file FILE | FILE)

This is an example.

positional arguments:
  positional_file  specifies a file.

optional arguments:
  -h, --help       show this help message and exit
  --file FILE      specifies a file.
stderr
run with ['abc']
run with ['--file', 'abc']
run with ['--file', 'abc', 'def']
usage: script [-h] (--file FILE | FILE)
script: error: argument positional_file: not allowed with argument --file
run with []
usage: script [-h] (--file FILE | FILE)
script: error: one of the arguments positional_file --file is required
run with ['-h']
run with ['-h', '1']
run with ['--help']