Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import time
  5. import tarfile
  6. import zipfile
  7.  
  8.  
  9. def __cf(word, coding="utf-8", to_str=False):
  10. """
  11. char format
  12. :param to_str: format in str. Default: False
  13. """
  14. if to_str:
  15. if isinstance(word, str):
  16. return word
  17.  
  18. if isinstance(word, unicode):
  19. try:
  20. return word.encode(coding)
  21. except UnicodeEncodeError:
  22. return __cf(word.encode("gbk"), to_str=True)
  23.  
  24. if isinstance(word, unicode):
  25. return word
  26.  
  27. if isinstance(word, str):
  28. try:
  29. return word.decode(coding)
  30. except UnicodeDecodeError:
  31. return __cf(word.decode("gbk"))
  32.  
  33.  
  34. class Compress(object):
  35. def __init__(self):
  36. self.tar_mode_map = dict(default="", gz="gz", bz2="bz2", bz="bz2")
  37.  
  38. @classmethod
  39. def tar(self, path, mode="bz2", **kwargs):
  40. var = ":".join("w", self.tar_mode_map[mode])
  41.  
  42. default_kwargs = dict(mode=var, encoding="gbk", ignore_zeros=True)
  43. default_kwargs.update(kwargs)
  44.  
  45. filename = os.path.join(os.getcwd(), os.path.basename(path) + "_v%s.tar.bz2" % int(time.time()))
  46. with tarfile.open(__cf(filename), **default_kwargs) as tar_obj:
  47. tar_obj.add(__cf(path), arcname=os.path.basename(path), recursive=True)
  48.  
  49. @staticmethod
  50. def zip(self):
  51. """
  52. python -m zipfile -c monty.zip life-of-brian_1979/
  53. """
  54. pass
  55.  
  56.  
  57. class Decompress(object):
  58. def __init__(self):
  59. self.tar_mode_map = dict(default="", gz="gz", bz2="bz2", bz="bz2")
  60.  
  61. @classmethod
  62. def tar(self, path, mode="bz2", encoding="gbk", **kwargs):
  63. var = ":".join("r", self.tar_mode_map[mode])
  64.  
  65. with tarfile.open(path, mode=mode, encoding=encoding) as tar_obj:
  66. tar_obj.extractall()
  67.  
  68. @staticmethod
  69. def zip(sdir, ddir=os.getcwd()):
  70. """
  71. python -m zipfile -e monty.zip target-dir/
  72. """
  73. with zipfile.ZipFile(sdir, "r") as zip_obj:
  74. zip_obj.extractall(ddir)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement