utils.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import argparse
  2. import functools
  3. import subprocess
  4. def read_file(fname):
  5. with open(fname, encoding='utf-8') as f:
  6. return f.read()
  7. def write_file(fname, content, mode='w'):
  8. with open(fname, mode, encoding='utf-8') as f:
  9. return f.write(content)
  10. def read_version(fname='yt_dlp/version.py', varname='__version__'):
  11. """Get the version without importing the package"""
  12. items = {}
  13. exec(compile(read_file(fname), fname, 'exec'), items)
  14. return items[varname]
  15. def get_filename_args(has_infile=False, default_outfile=None):
  16. parser = argparse.ArgumentParser()
  17. if has_infile:
  18. parser.add_argument('infile', help='Input file')
  19. kwargs = {'nargs': '?', 'default': default_outfile} if default_outfile else {}
  20. parser.add_argument('outfile', **kwargs, help='Output file')
  21. opts = parser.parse_args()
  22. if has_infile:
  23. return opts.infile, opts.outfile
  24. return opts.outfile
  25. def compose_functions(*functions):
  26. return lambda x: functools.reduce(lambda y, f: f(y), functions, x)
  27. def run_process(*args, **kwargs):
  28. kwargs.setdefault('text', True)
  29. kwargs.setdefault('check', True)
  30. kwargs.setdefault('capture_output', True)
  31. if kwargs['text']:
  32. kwargs.setdefault('encoding', 'utf-8')
  33. kwargs.setdefault('errors', 'replace')
  34. return subprocess.run(args, **kwargs)