Subversion Repositories programming

Rev

Rev 368 | Rev 373 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 368 Rev 371
Line 1... Line 1...
1
#!/usr/bin/env python
1
#!/usr/bin/env python
2
 
2
 
3
# Copyright: Ira W. Snyder (devel@irasnyder.com)
3
# Copyright: Ira W. Snyder (devel@irasnyder.com)
4
# License: GNU General Public License v2 (or at your option, any later version)
4
# License: GNU General Public License v2 (or at your option, any later version)
5
 
5
 
-
 
6
import os
-
 
7
import re
-
 
8
import sys
-
 
9
import errno
6
import os, re, shutil, sys
10
import shutil
7
from optparse import OptionParser
11
from optparse import OptionParser
8
 
12
 
9
### Default Configuration Variables ###
13
### Default Configuration Variables ###
10
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
14
DICT_FILE = '~/.config/animesorter2/animesorter.dict'
11
WORK_DIR =  '~/downloads/usenet'
15
WORK_DIR =  '~/downloads/usenet'
Line 25... Line 29...
25
    print 'Moved %s to %s' % (f, t)
29
    print 'Moved %s to %s' % (f, t)
26
 
30
 
27
def print_move_file_fail(f, t):
31
def print_move_file_fail(f, t):
28
    print 'FAILED to move %s to %s' % (f, t)
32
    print 'FAILED to move %s to %s' % (f, t)
29
 
33
 
-
 
34
def print_move_file_pretend (f, t):
-
 
35
    print 'Will move %s to %s' % (f, t)
-
 
36
 
30
def print_dir_create_suc(d):
37
def print_dir_create_suc(d):
31
    print 'Created directory %s' % (d, )
38
    print 'Created directory %s' % (d, )
32
 
39
 
33
def print_dir_create_fail(d):
40
def print_dir_create_fail(d):
34
    print 'Failed to create directory %s' % (d, )
41
    print 'Failed to create directory %s' % (d, )
35
 
42
 
-
 
43
def print_dir_create_pretend (d):
-
 
44
    print 'Will create directory %s' % (d, )
-
 
45
 
36
def print_dict_suc(dic, num):
46
def print_dict_suc(dic, num):
37
    print 'Successfully loaded %d records from %s\n' % (num, dic)
47
    print 'Successfully loaded %d records from %s\n' % (num, dic)
38
 
48
 
39
def print_dict_fail(dic):
49
def print_dict_fail(dic):
40
    print 'Opening dictionary: %s FAILED' % (dic, )
50
    print 'Opening dictionary: %s FAILED' % (dic, )
Line 108... Line 118...
108
        Returns a list of the files matching the pattern as type sre.SRE_Match."""
118
        Returns a list of the files matching the pattern as type sre.SRE_Match."""
109
 
119
 
110
        matches = [m for m in files if pattern.search(m)]
120
        matches = [m for m in files if pattern.search(m)]
111
        return matches
121
        return matches
112
 
122
 
-
 
123
    def as_makedirs (self, dirname):
-
 
124
        """Call os.makedirs(dirname), but check first whether we are in pretend
-
 
125
           mode, or if we're running interactively."""
-
 
126
 
-
 
127
        if not os.path.isdir (dirname):
-
 
128
            
-
 
129
            if self.options.pretend:
-
 
130
                print_dir_create_pretend (dirname)
-
 
131
                return 0
-
 
132
 
-
 
133
            if self.get_user_choice ('Make directory?: %s' % (dirname, )):
-
 
134
            
-
 
135
                try:
-
 
136
                    os.makedirs (dirname)
-
 
137
                    print_dir_create_suc (dirname)
-
 
138
                except:
-
 
139
                    print_dir_create_fail (dirname)
-
 
140
                    return errno.EIO
-
 
141
 
-
 
142
        return 0
-
 
143
 
-
 
144
    def as_move_single_file (self, f, fromdir, todir):
-
 
145
        """Move the single file named $f from the directory $fromdir to the
-
 
146
           directory $todir"""
-
 
147
 
-
 
148
        srcname = os.path.join (fromdir, f)
-
 
149
        dstname = os.path.join (todir, f)
-
 
150
        
-
 
151
        if self.options.pretend:
-
 
152
            print_move_file_pretend (f, todir)
-
 
153
            return 0 # success
-
 
154
 
-
 
155
        if self.get_user_choice ('Move file?: %s --> %s' % (srcname, dstname)):
-
 
156
            try:
-
 
157
                shutil.move (srcname, dstname)
-
 
158
                print_move_file_suc (f, todir)
-
 
159
            except:
-
 
160
                print_move_file_fail (f, todir)
-
 
161
                return errno.EIO
-
 
162
 
-
 
163
        return 0
-
 
164
 
113
    def move_files(self, files, fromdir, todir):
165
    def move_files(self, files, fromdir, todir):
114
        """move_files(files, fromdir, todir):
166
        """move_files(files, fromdir, todir):
115
        Move the files represented by the list FILES from FROMDIR to TODIR"""
167
        Move the files represented by the list FILES from FROMDIR to TODIR"""
-
 
168
 
-
 
169
        ret = 0
-
 
170
 
116
        ## Check for a non-default directory
171
        ## Check for a non-default directory
117
        if todir[0] != '/':
172
        if todir[0] != '/':
118
            todir = os.path.join(self.options.output_dir, todir)
173
            todir = os.path.join(self.options.output_dir, todir)
119
 
174
 
120
        ## Create the directory if it doesn't exist
175
        ## Create the directory if it doesn't exist
121
        if not os.path.isdir(todir):
176
        ret = self.as_makedirs (todir)
-
 
177
 
122
            try:
178
        if ret:
123
                if self.get_user_choice('Make directory?: %s' % (todir, )):
179
            # we cannot continue, since we can't make the directory
124
                    os.makedirs(todir)
-
 
125
                    print_dir_create_suc (todir)
-
 
126
            except:
180
            return ret
127
                print_dir_create_fail (todir)
-
 
128
 
181
 
129
        ## Try to move every file, one at a time
182
        ## Try to move every file, one at a time
130
        for f in files:
183
        for f in files:
131
            srcname = os.path.join(fromdir, f)
184
            ret = self.as_move_single_file (f, fromdir, todir)
132
            dstname = os.path.join(todir, f)
-
 
133
 
185
 
134
            try:
186
            if ret:
135
                if self.get_user_choice('Move file?: %s --> %s' % (srcname, dstname)):
-
 
136
                    shutil.move(srcname, dstname)
-
 
137
                    print_move_file_suc (f, todir)
187
                # something bad happened when moving a file
138
            except:
188
                break
139
                print_move_file_fail (f, todir)
-
 
140
 
189
 
-
 
190
        return ret
141
 
191
 
142
    def __dir_walker(self, dict, root, dirs, files):
192
    def __dir_walker(self, dict, root, dirs, files):
143
 
193
 
144
        ## Get all of the files in the directory that are of the correct types
194
        ## Get all of the files in the directory that are of the correct types
145
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
195
        types_re = re.compile(TYPES_REGEX, re.IGNORECASE)
Line 160... Line 210...
160
            return True
210
            return True
161
 
211
 
162
        # Get the user's choice since we're not in interactive mode
212
        # Get the user's choice since we're not in interactive mode
163
        done = False
213
        done = False
164
        while not done:
214
        while not done:
165
            s = raw_input('%s [y/n]: ' % (prompt, )).lower()
215
            s = raw_input('%s [y/N]: ' % (prompt, )).lower()
166
 
216
 
167
            if s == 'y' or s == 'yes':
217
            if s == 'y' or s == 'yes':
168
                return True
218
                return True
169
 
219
 
170
            if s == 'n' or s == 'no':
220
            if s == 'n' or s == 'no' or s == '':
171
                return False
221
                return False
172
 
222
 
173
            print 'Response not understood, try again.'
223
            print 'Response not understood, try again.'
174
 
224
 
175
    def main(self):
225
    def main(self):
Line 192... Line 242...
192
### MAIN IS HERE ###
242
### MAIN IS HERE ###
193
def main():
243
def main():
194
 
244
 
195
    ### Get the program options
245
    ### Get the program options
196
    parser = OptionParser()
246
    parser = OptionParser()
197
    parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
247
    #parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
198
            default=True, help='Don\'t print status messages to stdout')
248
    #        default=True, help='Don\'t print status messages to stdout')
199
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
249
    parser.add_option('-d', '--dict', dest='dict_file', default=DICT_FILE,
200
            help='Read dictionary from FILE', metavar='FILE')
250
            help='Read dictionary from FILE', metavar='FILE')
201
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
251
    parser.add_option('-n', '--not-recursive', action='store_false', dest='recursive',
202
            default=True, help='don\'t run recursively')
252
            default=True, help='don\'t run recursively')
203
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
253
    parser.add_option('-s', '--start-dir', dest='start_dir', default=WORK_DIR,
204
            help='Start running at directory DIR', metavar='DIR')
254
            help='Start running at directory DIR', metavar='DIR')
205
    parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
255
    parser.add_option('-o', '--output-dir', dest='output_dir', default=SORT_DIR,
206
            help='Sort files into DIR', metavar='DIR')
256
            help='Sort files into DIR', metavar='DIR')
207
    parser.add_option('-i', '--interactive', dest='interactive', default=False,
257
    parser.add_option('-i', '--interactive', dest='interactive', default=False,
208
            help='Confirm each move', action='store_true')
258
            help='Confirm each move', action='store_true')
-
 
259
    parser.add_option('-p', '--pretend', dest='pretend', default=False,
-
 
260
            help='Enable pretend mode', action='store_true')
209
 
261
 
210
    ## Parse the options
262
    ## Parse the options
211
    (options, args) = parser.parse_args()
263
    (options, args) = parser.parse_args()
212
 
264
 
213
    ## Correct directories
265
    ## Correct directories