forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
75 lines (54 loc) · 1.79 KB
/
command.py
File metadata and controls
75 lines (54 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os
verbose = True
class RenameFile:
def __init__(self, src, dest):
self.src = src
self.dest = dest
def execute(self):
if verbose:
print(f"[renaming '{self.src}' to '{self.dest}']")
os.rename(self.src, self.dest)
def undo(self):
if verbose:
print(f"[renaming '{self.dest}' back to '{self.src}']")
os.rename(self.dest, self.src)
class CreateFile:
def __init__(self, path, txt='hello world\n'):
self.path = path
self.txt = txt
def execute(self):
if verbose:
print(f"[creating file '{self.path}']")
with open(self.path, mode='w', encoding='utf-8') as out_file:
out_file.write(self.txt)
def undo(self):
delete_file(self.path)
class ReadFile:
def __init__(self, path):
self.path = path
def execute(self):
if verbose:
print(f"[reading file '{self.path}']")
with open(self.path, mode='r', encoding='utf-8') as in_file:
print(in_file.read(), end='')
def delete_file(path):
if verbose:
print(f"deleting file {path}")
os.remove(path)
def main():
orig_name, new_name = 'file1', 'file2'
commands = (CreateFile(orig_name),
ReadFile(orig_name),
RenameFile(orig_name, new_name))
[c.execute() for c in commands]
answer = input('reverse the executed commands? [y/n] ')
if answer not in 'yY':
print(f"the result is {new_name}")
exit()
for c in reversed(commands):
try:
c.undo()
except AttributeError as e:
print("Error", str(e))
if __name__ == "__main__":
main()