extract_from_cab.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Extracts a single file from a CAB archive."""
  6. import os
  7. import shutil
  8. import subprocess
  9. import sys
  10. import tempfile
  11. def run_quiet(*args):
  12. """Run 'expand' supressing noisy output. Returns returncode from process."""
  13. popen = subprocess.Popen(args, stdout=subprocess.PIPE)
  14. out, _ = popen.communicate()
  15. if popen.returncode:
  16. # expand emits errors to stdout, so if we fail, then print that out.
  17. print out
  18. return popen.returncode
  19. def main():
  20. if len(sys.argv) != 4:
  21. print 'Usage: extract_from_cab.py cab_path archived_file output_dir'
  22. return 1
  23. [cab_path, archived_file, output_dir] = sys.argv[1:]
  24. # Expand.exe does its work in a fixed-named temporary directory created within
  25. # the given output directory. This is a problem for concurrent extractions, so
  26. # create a unique temp dir within the desired output directory to work around
  27. # this limitation.
  28. temp_dir = tempfile.mkdtemp(dir=output_dir)
  29. try:
  30. # Invoke the Windows expand utility to extract the file.
  31. level = run_quiet('expand', cab_path, '-F:' + archived_file, temp_dir)
  32. if level == 0:
  33. # Move the output file into place, preserving expand.exe's behavior of
  34. # paving over any preexisting file.
  35. output_file = os.path.join(output_dir, archived_file)
  36. try:
  37. os.remove(output_file)
  38. except OSError:
  39. pass
  40. os.rename(os.path.join(temp_dir, archived_file), output_file)
  41. finally:
  42. shutil.rmtree(temp_dir, True)
  43. if level != 0:
  44. return level
  45. # The expand utility preserves the modification date and time of the archived
  46. # file. Touch the extracted file. This helps build systems that compare the
  47. # modification times of input and output files to determine whether to do an
  48. # action.
  49. os.utime(os.path.join(output_dir, archived_file), None)
  50. return 0
  51. if __name__ == '__main__':
  52. sys.exit(main())