writer.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import sys, os
  2. import argparse
  3. # Explicitly enable local imports
  4. # Don't forget to add imported scripts to inputs of the calling command!
  5. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  6. import process_command_files as pcf
  7. def parse_args():
  8. args = pcf.get_args(sys.argv[1:])
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument('-f', '--file', dest='file_path')
  11. parser.add_argument('-a', '--append', action='store_true', default=False)
  12. parser.add_argument('-Q', '--quote', action='store_true', default=False)
  13. parser.add_argument('-s', '--addspace', action='store_true', default=False)
  14. parser.add_argument('-c', '--content', action='append', dest='content')
  15. parser.add_argument('-m', '--content-multiple', nargs='*', dest='content')
  16. parser.add_argument('-P', '--path-list', action='store_true', default=False)
  17. return parser.parse_args(args)
  18. def smart_shell_quote(v):
  19. if v is None:
  20. return None
  21. if ' ' in v or '"' in v or "'" in v:
  22. return "\"{0}\"".format(v.replace('"', '\\"'))
  23. return v
  24. if __name__ == '__main__':
  25. args = parse_args()
  26. open_type = 'a' if args.append else 'w'
  27. content = args.content
  28. if args.quote:
  29. content = [smart_shell_quote(ln) for ln in content] if content is not None else None
  30. content = '\n'.join(content)
  31. with open(args.file_path, open_type) as f:
  32. if args.addspace:
  33. f.write(' ')
  34. if content is not None:
  35. f.write(content)