-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxero.py
executable file
·79 lines (65 loc) · 2.07 KB
/
xero.py
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
76
77
78
79
#!/usr/bin/env python3
"""
truncate files
V1.0 [2022.14MeV]
"""
import argparse
import os
import sys
def parse_arguments():
"""parse the argument list, build help and usage messages
Command-Line Arguments
-h
-v
FILES
Returns:
namespace (ns): namespace with the arguments passed and their values
"""
parser = argparse.ArgumentParser(
description='truncate a file to zero size')
# if omitted, the default value is returned, so arg.input is always defined
parser.add_argument('files',
action='store',
help='file to truncate',
nargs="+", # at least one file on command line to truncate
)
parser.add_argument('-s', '--silent',
action="store_true",
help='don\'t show files being truncated',
required=False,
)
args = parser.parse_args()
return args # namespace containing the argument passed on the command line
def main():
""" parse command line for files and truncate them
:return:
"""
prog = os.path.basename(sys.argv[0])
args = parse_arguments()
# walk through files passed by argument, open them truncated, and close them
error_found = False
for file in args.files:
if not os.path.exists(file):
print(f'{prog} -- file {file} not found')
error_found = True
continue
if not os.path.isfile(file):
print(f'{prog} -- file {file} not a file')
error_found = True
continue
# returns PermissionError if x can't be read
try:
with open(file, 'a') as f:
f.truncate(0)
except PermissionError:
print(f"{prog}: can't write {file}")
error_found = True
continue
if not args.silent:
print(f' >>{prog}: zeroed {file}')
if error_found:
return 2
else:
return 0
if __name__ == '__main__':
sys.exit(main())