Welcome, guest | Sign In | My Account | Store | Cart

For those who would want to search the message logs produced by recipe 577638, this program provides a command-line solution to searching messages according to their authors. If this program is placed in the message directory, the program may be executed on the command-line with the author's name as an argument. If and when the program is executed without an argument, usage information is shown on the screen before exiting. If an author was not found, the author's name is printed stating that nothing could be found. If a matching file was found, all timestamps and messages will be displayed that could be decoded correctly.

If there are any recommendation for this recipe or if anyone wishes to down-vote this recipe, please provide corrective criticism showing the the program's faults and give suggestions on how you would fix any problems that it might have.

Python, 40 lines
 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
import sys
import os

FILE = os.path.basename(sys.argv[0])

def main():
    identity = get_identity()
    text = get_messages(identity)
    print_messages(text)

def get_identity():
    try:
        return sys.argv[1]
    except IndexError:
        print('Usage: {} <identity>'.format(FILE))
        sys.exit()

def get_messages(identity):
    for name in os.listdir('.'):
        if os.path.isfile(name) and name != FILE:
            with open(name) as file:
                title, text = file.read().split('\0', 1)
                if title == identity:
                    return text
    print(repr(identity), 'not found.')
    sys.exit()

def print_messages(text):
    message = iter(text.split('\0'))
    try:
        while True:
            try:
                print('[{}] {}'.format(next(message), next(message)))
            except UnicodeEncodeError:
                pass
    except StopIteration:
        pass

if __name__ == '__main__':
    main()