]> git.ipfire.org Git - thirdparty/kernel/stable-queue.git/blame - scripts/splitmbox.py
scripts: more updates
[thirdparty/kernel/stable-queue.git] / scripts / splitmbox.py
CommitLineData
93598721 1#! /usr/bin/env python3
56d43432
GKH
2""" Split a Unix-style mailbox into individual files
3
4Written by Aquarius <aquarius@kryogenix.org>
5Usage: splitmbox.py <mailbox-file> <directory>
6
7This will create files numbered 01,02,03... in <directory>. The
8number of prefixed zeroes will make all filenames in the
9directory the same length. """
10
11import mailbox,sys,getopt,string,os,subprocess
12
13VERSION = '0.1'
14USAGE = """Usage: splitmbox.py [ OPTION ] <mailbox-file> <directory>
15
16 -h, --help
17 Show this help text and exit
18 -v, --version
19 Show file version and exit
20
21This will create files numbered 01,02,03... in <directory>. The
22number of prefixed zeroes will make all filenames in the
23directory the same length. """
24
25
26try:
27 optlist, args = getopt.getopt(sys.argv[1:],'hv',['help','version'])
28except getopt.error, error_text:
29 print error_text,'\n'
30 print USAGE
31 sys.exit(1)
32
33for tuple in optlist:
34 if tuple[0] == '-h' or tuple[0] == '--help':
35 print USAGE
36 sys.exit(0)
37 if tuple[0] == '-v' or tuple[0] == '--version':
38 print VERSION
39 sys.exit(0)
40
41if len(args) != 2:
42 print USAGE
43
44mbox_fname, output_dir = args
45if output_dir[-1] != '/':
46 output_dir = output_dir + '/'
47
48# Make the output directory, if required
49try:
50 os.mkdir(output_dir)
51except os.error,ertxt:
52 if string.find(str(ertxt),'File exists') == -1:
53 print 'Failed to create or use directory',output_dir,'[',ertxt,']'
54 sys.exit(1)
55
56try:
57 mbox_file = open(mbox_fname)
58except:
59 print "Failed to open file",mbox_fname
60 sys.exit(1)
61
62mbox = mailbox.UnixMailbox(mbox_file)
63
64# Find out how many messages in the mailbox
65count = 0
66while 1:
67 msg = mbox.next()
68 if not msg:
69 break
70 count = count + 1
71
72# Now do it again, outputting files
73
74mbox_file.close()
75mbox_file = open(mbox_fname)
76mbox = mailbox.UnixMailbox(mbox_file)
77
93598721
GKH
78digits = len(str(count))
79#digits = 3
56d43432
GKH
80count = 0
81while 1:
82 msg = mbox.next()
83 if not msg:
84 break
85 fname = output_dir+'msg.'+('0'*digits+str(count))[-digits:]
86 print 'Writing ', fname
87 outfile = open(fname,'w')
88 outfile.write('From foo@baz ');
89 outfile.write(subprocess.check_output('date'));
90 for s in msg.headers:
91 outfile.write(s)
92 outfile.write('\n')
93 for s in msg.fp.readlines():
94 outfile.write(s)
95 outfile.close()
96 count = count + 1