command.py 1004 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. class MoveFileCommand(object):
  5. def __init__(self, src, dest):
  6. self.src = src
  7. self.dest = dest
  8. def execute(self):
  9. print('renaming {} to {}'.format(self.src, self.dest))
  10. os.rename(self.src, self.dest)
  11. def undo(self):
  12. print('renaming {} to {}'.format(self.dest, self.src))
  13. os.rename(self.dest, self.src)
  14. def main():
  15. command_stack = []
  16. # commands are just pushed into the command stack
  17. command_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
  18. command_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
  19. # they can be executed later on
  20. for cmd in command_stack:
  21. cmd.execute()
  22. # and can also be undone at will
  23. for cmd in reversed(command_stack):
  24. cmd.undo()
  25. if __name__ == "__main__":
  26. main()
  27. ### OUTPUT ###
  28. # renaming foo.txt to bar.txt
  29. # renaming bar.txt to baz.txt
  30. # renaming baz.txt to bar.txt
  31. # renaming bar.txt to foo.txt