#!/usr/bin/env python# -*- coding: utf-8 -*-import osfrom os.path import lexistsclass MoveFileCommand(object):def __init__(self, src, dest):self.src = srcself.dest = destdef execute(self):self.rename(self.src, self.dest)def undo(self):self.rename(self.dest, self.src)def rename(self, src, dest):print('renaming {} to {}'.format(src, dest))os.rename(src, dest)def main():command_stack = []# commands are just pushed into the command stackcommand_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))command_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))# verify that none of the target files existassert(not lexists("foo.txt"))assert(not lexists("bar.txt"))assert(not lexists("baz.txt"))try:with open("foo.txt", "w"): # Creating the filepass# they can be executed later onfor cmd in command_stack:cmd.execute()# and can also be undone at willfor cmd in reversed(command_stack):cmd.undo()finally:os.unlink("foo.txt")if __name__ == "__main__":main()### OUTPUT #### renaming foo.txt to bar.txt# renaming bar.txt to baz.txt# renaming baz.txt to bar.txt# renaming bar.txt to foo.txt
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。