You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.3 KiB

4 years ago
  1. #!/usr/bin/python3
  2. from __future__ import with_statement
  3. import os
  4. import sys
  5. import shlex
  6. import plac
  7. def run(fnames, cmd, verbose):
  8. "Run batch scripts and tests"
  9. for fname in fnames:
  10. with open(fname) as f:
  11. lines = list(f)
  12. if not lines[0].startswith('#!'):
  13. sys.exit('Missing or incorrect shebang line!')
  14. firstline = lines[0][2:] # strip the shebang
  15. init_args = shlex.split(firstline)
  16. tool = plac.import_main(*init_args)
  17. command = getattr(plac.Interpreter(tool), cmd) # doctest or execute
  18. if verbose:
  19. sys.stdout.write('Running %s with %s' % (fname, firstline))
  20. command(lines[1:], verbose=verbose)
  21. @plac.annotations(
  22. verbose=('verbose mode', 'flag', 'v'),
  23. interactive=('run plac tool in interactive mode', 'flag', 'i'),
  24. multiline=('run plac tool in multiline mode', 'flag', 'm'),
  25. serve=('run plac server', 'option', 's', int),
  26. batch=('run plac batch files', 'flag', 'b'),
  27. test=('run plac test files', 'flag', 't'),
  28. fname='script to run (.py or .plac or .placet)',
  29. extra='additional arguments',
  30. )
  31. def main(verbose, interactive, multiline, serve, batch, test, fname=None,
  32. *extra):
  33. "Runner for plac tools, plac batch files and plac tests"
  34. baseparser = plac.parser_from(main)
  35. if fname is None:
  36. baseparser.print_help()
  37. elif sys.argv[1] == fname: # script mode
  38. plactool = plac.import_main(fname)
  39. plactool.prog = os.path.basename(sys.argv[0]) + ' ' + fname
  40. out = plac.call(plactool, sys.argv[2:], eager=False)
  41. if plac.iterable(out):
  42. for output in out:
  43. print(output)
  44. else:
  45. print(out)
  46. elif interactive or multiline or serve:
  47. plactool = plac.import_main(fname, *extra)
  48. plactool.prog = ''
  49. i = plac.Interpreter(plactool)
  50. if interactive:
  51. i.interact(verbose=verbose)
  52. elif multiline:
  53. i.multiline(verbose=verbose)
  54. elif serve:
  55. i.start_server(serve)
  56. elif batch:
  57. run((fname,) + extra, 'execute', verbose)
  58. elif test:
  59. run((fname,) + extra, 'doctest', verbose)
  60. print('run %s plac test(s)' % (len(extra) + 1))
  61. else:
  62. baseparser.print_usage()
  63. main.add_help = False
  64. if __name__ == '__main__':
  65. plac.call(main)