command.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. self()
  10. def __call__(self):
  11. print('renaming {} to {}'.format(self.src, self.dest))
  12. os.rename(self.src, self.dest)
  13. def undo(self):
  14. print('renaming {} to {}'.format(self.dest, self.src))
  15. os.rename(self.dest, self.src)
  16. def main():
  17. command_stack = []
  18. # commands are just pushed into the command stack
  19. command_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
  20. command_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
  21. # they can be executed later on
  22. for cmd in command_stack:
  23. cmd.execute()
  24. # and can also be undone at will
  25. for cmd in reversed(command_stack):
  26. cmd.undo()
  27. if __name__ == "__main__":
  28. main()
  29. ### OUTPUT ###
  30. # renaming foo.txt to bar.txt
  31. # renaming bar.txt to baz.txt
  32. # renaming baz.txt to bar.txt
  33. # renaming bar.txt to foo.txt