fork(3) download
  1. from __future__ import print_function
  2.  
  3. script = """
  4.  
  5. import argparse
  6. import sys
  7.  
  8. parser = argparse.ArgumentParser(description="This is an example.")
  9. parser.add_argument('file', nargs='?', default='', help='specifies a file.')
  10. parser.add_argument('--file', help='specifies a file.')
  11.  
  12. args = parser.parse_args()
  13. print("{} -> {}".format(sys.argv[1:], args))
  14.  
  15. # check for file argument
  16. if not args.file:
  17. raise Exception('Missing "file" argument')
  18. """
  19. import shlex
  20. import sys
  21. from subprocess import Popen, PIPE, STDOUT
  22.  
  23. for line in sys.stdin:
  24. args = shlex.split(line)
  25. print("run with {}".format(args))
  26. p = Popen([sys.executable, "-c", script] + args, stdout=PIPE, stderr=STDOUT)
  27. print(p.communicate()[0].decode())
Success #stdin #stdout 0.72s 10040KB
stdin
abc
--file abc

--file abc def
stdout
run with ['abc']
['abc'] -> Namespace(file='abc')

run with ['--file', 'abc']
['--file', 'abc'] -> Namespace(file='')
Traceback (most recent call last):
  File "<string>", line 15, in <module>
Exception: Missing "file" argument

run with []
[] -> Namespace(file='')
Traceback (most recent call last):
  File "<string>", line 15, in <module>
Exception: Missing "file" argument

run with ['--file', 'abc', 'def']
['--file', 'abc', 'def'] -> Namespace(file='def')