touch.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. import optparse
  3. import os
  4. import sys
  5. import time
  6. def main(argv):
  7. parser = optparse.OptionParser(add_help_option=False)
  8. parser.disable_interspersed_args()
  9. parser.add_option('-?', '--help', dest='help', action='store_true', default=None, help='print help')
  10. parser.add_option('-t', dest='t', action='store', default=None)
  11. opts, argv_rest = parser.parse_args(argv)
  12. if getattr(opts, 'help', False):
  13. parser.print_help()
  14. return 0
  15. tspec = opts.t
  16. if tspec is None:
  17. times = None
  18. else:
  19. head, sep, tail = tspec.partition('.')
  20. if 8 > len(head):
  21. raise Exception("time spec must follow format [[CC]YY]MMDDhhmm[.SS]: " + tspec + '; ' + head)
  22. tfmt = ''
  23. if 12 == len(head):
  24. tfmt += '%Y'
  25. elif 10 == len(head):
  26. tfmt += '%y'
  27. tfmt += '%m%d%H%M'
  28. if 2 == len(tail):
  29. tfmt += '.%S'
  30. mtime = time.mktime(time.strptime(tspec, tfmt))
  31. times = (mtime, mtime)
  32. for file in argv_rest:
  33. try:
  34. os.utime(file, times)
  35. except:
  36. open(file, 'w').close()
  37. if times is not None:
  38. os.utime(file, times)
  39. if __name__ == '__main__':
  40. sys.exit(main(sys.argv[1:]))