touch.py 1.3 KB

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