command.py 986 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import os
  2. class MoveFileCommand(object):
  3. def __init__(self, src, dest):
  4. self.src = src
  5. self.dest = dest
  6. def execute(self):
  7. self()
  8. def __call__(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. if __name__ == "__main__":
  15. undo_stack = []
  16. ren1 = MoveFileCommand('foo.txt', 'bar.txt')
  17. ren2 = MoveFileCommand('bar.txt', 'baz.txt')
  18. # commands are just pushed into the command stack
  19. for cmd in ren1, ren2:
  20. undo_stack.append(cmd)
  21. # they can be executed later on will
  22. for cmd in undo_stack:
  23. cmd.execute() # foo.txt is now renamed to baz.txt
  24. # and can also be undone on will
  25. for cmd in undo_stack:
  26. undo_stack.pop().undo() # Now it's bar.txt
  27. undo_stack.pop().undo() # and back to foo.txt