command.py 859 B

12345678910111213141516171819202122232425262728293031323334353637
  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. 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()