OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python2 | |
2 | |
3 import argparse | |
4 import os | |
5 import sys | |
6 | |
7 from utils import shellcmd | |
8 | |
9 def GetFileAttributes(Filename): | |
10 """Returns the set of names contained in file named Filename. | |
11 """ | |
12 if not os.path.isfile(Filename): | |
13 raise RuntimeError("Can't open: %s" % Filename) | |
14 with open(Filename, 'r') as f: | |
15 return f.read().split() | |
16 | |
17 def HasFileAttributes(Filename, Attributes): | |
18 """Returns true if the set of names in Attributes also appear | |
19 in the set of names contained in file named Filename. | |
20 """ | |
21 return set(Attributes) <= set(GetFileAttributes(Filename)) | |
22 | |
23 def main(): | |
24 """Check if the set attributes (i.e. names), contained in FILE, | |
25 contains the attributes defined by --att=ATTRIBUTE arguments. If | |
26 so, runs in a shell the command defined by the remaining | |
27 arguments | |
Jim Stichnoth
2014/10/21 21:58:41
end with a period.
Karl
2014/10/22 17:03:36
Done.
| |
28 """ | |
29 argparser = argparse.ArgumentParser( | |
30 description=' ' + main.__doc__, | |
31 formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
32 argparser.add_argument('file', metavar='FILE', | |
33 help='File defining attributes to check against.') | |
34 argparser.add_argument('--att', required=False, default=[], | |
35 action='append', metavar='ATTRIBUTE', | |
36 help='Attribute to check. May be repeated.') | |
37 argparser.add_argument('--echo-cmd', required=False, | |
38 action='store_true', | |
39 help='Trace the command before running.') | |
40 argparser.add_argument('--command', nargs=argparse.REMAINDER, | |
41 help='Command to run if attributes found.') | |
42 | |
43 args = argparser.parse_args() | |
44 | |
45 # Quit early if no command to run. | |
46 if not args.command: | |
47 raise RuntimeError("No command argument(s) specified for ifatts") | |
48 | |
49 if HasFileAttributes(args.file, args.att): | |
50 stdout_result = shellcmd(args.command, echo=args.echo_cmd) | |
51 if not args.echo_cmd: | |
52 sys.stdout.write(stdout_result) | |
53 | |
54 if __name__ == '__main__': | |
55 main() | |
56 sys.exit(0) | |
OLD | NEW |