~ubuntu-branches/ubuntu/karmic/spambayes/karmic

« back to all changes in this revision

Viewing changes to utilities/splitndirs.py

  • Committer: Bazaar Package Importer
  • Author(s): Jorge Bernal
  • Date: 2005-04-07 14:02:02 UTC
  • Revision ID: james.westby@ubuntu.com-20050407140202-mgyh6t7gn2dlrrw5
Tags: upstream-1.0.1
ImportĀ upstreamĀ versionĀ 1.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
 
 
3
"""Split an mbox into N random directories of files.
 
4
 
 
5
Usage: %(program)s [-h] [-g] [-s seed] [-v] -n N sourcembox ... outdirbase
 
6
 
 
7
Options:
 
8
    -h / --help
 
9
        Print this help message and exit
 
10
 
 
11
    -g
 
12
        Do globbing on each sourcepath.  This is helpful on Windows, where
 
13
        the native shells don't glob, or when you have more mboxes than
 
14
        your shell allows you to specify on the commandline.
 
15
 
 
16
    -s seed
 
17
        Seed the random number generator with seed (an integer).
 
18
        By default, use system time at startup to seed.
 
19
 
 
20
    -v
 
21
        Verbose.  Displays a period for each 100 messages parsed.
 
22
        May display other stuff.
 
23
 
 
24
    -n N
 
25
        The number of output mboxes desired.  This is required.
 
26
 
 
27
Arguments:
 
28
    sourcembox
 
29
        The mbox or path to an mbox to split.
 
30
 
 
31
    outdirbase
 
32
        The base path + name prefix for each of the N output dirs.
 
33
        Output files have names of the form
 
34
            outdirbase + ("Set%%d/%%d" %% (i, n))
 
35
 
 
36
Example:
 
37
    %(program)s -s 123 -n5 Data/spam.mbox Data/Spam/Set
 
38
 
 
39
produces 5 directories, named Data/Spam/Set1 through Data/Spam/Set5.  Each
 
40
contains a random selection of the messages in spam.mbox, and together
 
41
they contain every message in spam.mbox exactly once.  Each has
 
42
approximately the same number of messages.  spam.mbox is not altered.  In
 
43
addition, the seed for the random number generator is forced to 123, so
 
44
that while the split is random, it's reproducible.
 
45
"""
 
46
 
 
47
import sys
 
48
import os
 
49
import random
 
50
import mailbox
 
51
import email
 
52
import getopt
 
53
import glob
 
54
 
 
55
from spambayes import mboxutils
 
56
 
 
57
try:
 
58
    True, False
 
59
except NameError:
 
60
    # Maintain compatibility with Python 2.2
 
61
    True, False = 1, 0
 
62
 
 
63
 
 
64
program = sys.argv[0]
 
65
 
 
66
def usage(code, msg=''):
 
67
    print >> sys.stderr, __doc__ % globals()
 
68
    if msg:
 
69
        print >> sys.stderr, msg
 
70
    sys.exit(code)
 
71
 
 
72
def main():
 
73
    try:
 
74
        opts, args = getopt.getopt(sys.argv[1:], 'hgn:s:v', ['help'])
 
75
    except getopt.error, msg:
 
76
        usage(1, msg)
 
77
 
 
78
    doglob = False
 
79
    n = None
 
80
    verbose = False
 
81
    for opt, arg in opts:
 
82
        if opt in ('-h', '--help'):
 
83
            usage(0)
 
84
        elif opt == '-g':
 
85
            doglob = True
 
86
        elif opt == '-s':
 
87
            random.seed(int(arg))
 
88
        elif opt == '-n':
 
89
            n = int(arg)
 
90
        elif opt == '-v':
 
91
            verbose = True
 
92
 
 
93
    if n is None or n <= 1:
 
94
        usage(1, "an -n value > 1 is required")
 
95
 
 
96
    if len(args) < 2:
 
97
        usage(1, "input mbox name and output base path are required")
 
98
    inputpaths, outputbasepath = args[:-1], args[-1]
 
99
 
 
100
    outdirs = [outputbasepath + ("%d" % i) for i in range(1, n+1)]
 
101
    for dir in outdirs:
 
102
        if not os.path.isdir(dir):
 
103
            os.makedirs(dir)
 
104
 
 
105
    counter = 0
 
106
    for inputpath in inputpaths:
 
107
        if doglob:
 
108
            inpaths = glob.glob(inputpath)
 
109
        else:
 
110
            inpaths = [inputpath]
 
111
 
 
112
        for inpath in inpaths:
 
113
            mbox = mboxutils.getmbox(inpath)
 
114
            for msg in mbox:
 
115
                i = random.randrange(n)
 
116
                astext = str(msg)
 
117
                #assert astext.endswith('\n')
 
118
                counter += 1
 
119
                msgfile = open('%s/%d' % (outdirs[i], counter), 'wb')
 
120
                msgfile.write(astext)
 
121
                msgfile.close()
 
122
                if verbose:
 
123
                    if counter % 100 == 0:
 
124
                        sys.stdout.write('.')
 
125
                        sys.stdout.flush()
 
126
 
 
127
    if verbose:
 
128
        print
 
129
        print counter, "messages split into", n, "directories"
 
130
 
 
131
if __name__ == '__main__':
 
132
    main()