summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJon Bergli Heier <snakebite@jvnv.net>2010-10-21 19:15:11 +0200
committerJon Bergli Heier <snakebite@jvnv.net>2010-10-21 19:15:11 +0200
commit58da4e434d844da76226fdaceb6952532d68fb1e (patch)
tree29787310fd7b8ee591f953a45d9b23a6f4c00b83
parent29a2c4c430cab5821580467ea69f8f9347d699b5 (diff)
Make code compatible with Python 3.x; should work with 2.6 and newer.
-rwxr-xr-xanidb54
-rw-r--r--pyanidb/__init__.py18
-rw-r--r--pyanidb/hash.py8
3 files changed, 44 insertions, 36 deletions
diff --git a/anidb b/anidb
index b88e6cc..ffc27ea 100755
--- a/anidb
+++ b/anidb
@@ -1,9 +1,17 @@
#!/usr/bin/env python
import pyanidb, pyanidb.hash
-import ConfigParser, optparse, os, sys, getpass
+try:
+ import ConfigParser
+except ImportError:
+ import configparser as ConfigParser
+import optparse, os, sys, getpass
from collections import deque
+# Workaround for input/raw_input
+if hasattr(__builtins__, 'raw_input'):
+ input = raw_input
+
# Colors.
red = lambda x: '\x1b[1;31m' + x + '\x1b[0m'
@@ -60,7 +68,7 @@ if options.cache:
try:
import xattr
except ImportError:
- print red('No xattr, caching disabled.')
+ print(red('No xattr, caching disabled.'))
options.cache = False
options.identify = options.identify or options.rename
options.login = options.add or options.watched or options.identify
@@ -71,7 +79,7 @@ if not options.format:
if options.login:
if not options.username:
- options.username = raw_input('Username: ')
+ options.username = input('Username: ')
if not options.password:
options.password = getpass.getpass()
@@ -82,12 +90,12 @@ remaining = deque(args)
while remaining:
name = remaining.popleft()
if not os.access(name, os.R_OK):
- print red('Invalid file:'), name
+ print('{0} {1}'.format(red('Invalid file:'), name))
elif os.path.isfile(name):
files.append(name)
elif os.path.isdir(name):
if not options.recursive:
- print red('Is a directory:'), name
+ print('{0} {1}'.format(red('Is a directory:'), name))
else:
for sub in sorted(os.listdir(name)):
if sub.startswith('.'):
@@ -99,7 +107,7 @@ while remaining:
remaining.appendleft(sub)
if not files:
- print blue('Nothing to do.')
+ print(blue('Nothing to do.'))
sys.exit(0)
# Authorization.
@@ -108,15 +116,15 @@ if options.login:
a = pyanidb.AniDB(options.username, options.password)
try:
a.auth()
- print blue('Logged in as user:'), options.username
+ print('{0} {1}'.format(blue('Logged in as user:'), options.username))
except pyanidb.AniDBUserError:
- print red('Invalid username/password.')
+ print(red('Invalid username/password.'))
sys.exit(1)
except pyanidb.AniDBTimeout:
- print red('Connection timed out.')
+ print(red('Connection timed out.'))
sys.exit(1)
- except pyanidb.AniDBError, e:
- print red('Fatal error:'), e
+ except pyanidb.AniDBError as e:
+ print('{0} {1}'.format(red('Fatal error:'), e))
sys.exit(1)
# Hashing.
@@ -124,7 +132,7 @@ if options.login:
hashed = unknown = 0
for file in pyanidb.hash.hash_files(files, options.cache, (('ed2k', 'md5', 'sha1', 'crc32') if options.multihash else ('ed2k',))):
- print blue('Hashed:'), 'ed2k://|file|%s|%d|%s|%s' % (file.name, file.size, file.ed2k, ' (cached)' if file.cached else '')
+ print('{0} ed2k://|file|{1}|{2}|{3}|{4}'.format(blue('Hashed:'), file.name, file.size, file.ed2k, ' (cached)' if file.cached else ''))
fid = (file.size, file.ed2k)
hashed += 1
@@ -132,16 +140,16 @@ for file in pyanidb.hash.hash_files(files, options.cache, (('ed2k', 'md5', 'sha1
# Multihash.
if options.multihash:
- print blue('MD5:'), file.md5
- print blue('SHA1:'), file.sha1
- print blue('CRC32:'), file.crc32
+ print('{0} {1}'.format(blue('MD5:'), file.md5))
+ print('{0} {1}'.format(blue('SHA1:'), file.sha1))
+ print('{0} {1}'.format(blue('CRC32:'), file.crc32))
# Identify.
if options.identify:
info = a.get_file(fid, ('gtag', 'romaji', 'epno', 'state', 'epromaji', 'crc32', 'filetype'), True)
fid = int(info['fid'])
- print green('Identified:'), '[%s] %s - %s - %s' % (info['gtag'], info['romaji'], info['epno'], info['epromaji'])
+ print('{0} [{1}] {2} - {3} - {4}'.format(green('Identified:'), info['gtag'], info['romaji'], info['epno'], info['epromaji']))
# Renaming.
@@ -155,34 +163,34 @@ for file in pyanidb.hash.hash_files(files, options.cache, (('ed2k', 'md5', 'sha1
'crc': info['crc32'],
'CRC': info['crc32'].upper(),
'suf': info['filetype']}
- for name, value in rename_data.iteritems():
+ for name, value in rename_data.items():
s = s.replace(r'%' + name, value)
if s[0] == '_':
s = s[1:].replace(' ', '_')
s = s.replace('/', '_')
- print yellow('Renaming to:'), s
+ print('{0} {1}'.format(yellow('Renaming to:'), s))
os.rename(file.name, os.path.join(os.path.split(file.name)[0], s))
# Adding.
if options.add:
a.add_file(fid, viewed = options.watched, retry = True)
- print green('Added to mylist.')
+ print(green('Added to mylist.'))
# Watched.
elif options.watched:
a.add_file(fid, viewed = True, edit = True, retry = True)
- print green('Marked watched.')
+ print(green('Marked watched.'))
except pyanidb.AniDBUnknownFile:
- print red('Unknown file.')
+ print(red('Unknown file.'))
unknown += 1
except pyanidb.AniDBNotInMylist:
- print red('File not in mylist.')
+ print(red('File not in mylist.'))
# Finished.
-print blue('Hashed %d files%s.' % (hashed, (', %d unknown' % unknown) if unknown else ''))
+print(blue('Hashed {0} files{1}.'.format(hashed, ', {0} unknown'.format(unknown) if unknown else '')))
diff --git a/pyanidb/__init__.py b/pyanidb/__init__.py
index d570345..6a3f222 100644
--- a/pyanidb/__init__.py
+++ b/pyanidb/__init__.py
@@ -2,7 +2,7 @@ import socket, time
protover = 3
client = 'pyanidb'
-clientver = 6
+clientver = 7
states = {
'unknown': 0,
@@ -25,7 +25,7 @@ acode = (
'short', 'synonym', 'category', '', '', '', '', '')
info = fcode + acode
-info = dict([(info[i], 1L << i) for i in xrange(len(info)) if info[i]])
+info = dict([(info[i], 1 << i) for i in range(len(info)) if info[i]])
class AniDBError(Exception):
pass
@@ -70,23 +70,23 @@ class AniDB:
self.sock.close()
def newver_msg(self):
- print 'New version available.'
+ print('New version available.')
def retry_msg(self):
- print 'Connection timed out, retrying.'
+ print('Connection timed out, retrying.')
def execute(self, cmd, args = None, retry = False):
if not args:
args = {}
while 1:
- data = '%s %s' % (cmd, '&'.join(['%s=%s' % a for a in args.iteritems()]))
+ data = '{0} {1}\n'.format(cmd, '&'.join(['{0}={1}'.format(*a) for a in args.items()]))
t = time.time()
if t < self.lasttime + 2:
time.sleep(self.lasttime + 2 - t)
self.lasttime = time.time()
- self.sock.sendto(data + '\n', self.server)
+ self.sock.sendto(data.encode(), 0, self.server)
try:
- data = self.sock.recv(8192).split('\n')
+ data = self.sock.recv(8192).decode().split('\n')
except socket.timeout:
if retry:
self.retry_msg()
@@ -132,9 +132,9 @@ class AniDB:
except TypeError:
args = {'fid': fid}
info_codes = list(info_codes)
- info_codes.sort(lambda x, y: cmp(info[x], info[y]))
+ info_codes.sort(key = lambda x: info[x])
info_code = sum([info[code] for code in info_codes])
- args.update({'s': self.session, 'fcode': info_code & 0xffffffffL, 'acode': info_code >> 32})
+ args.update({'s': self.session, 'fcode': info_code & 0xffffffff, 'acode': info_code >> 32})
while 1:
code, text, data = self.execute('FILE', args, retry)
if code == 220:
diff --git a/pyanidb/hash.py b/pyanidb/hash.py
index 912fc67..489f15a 100644
--- a/pyanidb/hash.py
+++ b/pyanidb/hash.py
@@ -35,7 +35,7 @@ class Crc32:
self.s = binascii.crc32(data, self.s)
def hexdigest(self):
- return '%08x' % (self.s & 0xffffffff)
+ return '{0:08x}'.format(self.s & 0xffffffff)
hasher_obj = {
'ed2k': Ed2k,
@@ -52,7 +52,7 @@ class Hash:
update_list.append(h.update)
setattr(self, a, h.hexdigest)
- f = open(filename)
+ f = open(filename, 'rb')
data = f.read(131072)
while data:
for u in update_list:
@@ -80,7 +80,7 @@ class File:
cache = dict([(n[13:], xattr.getxattr(self.name, n)) for n in xattr.listxattr(self.name) if n.startswith('user.pyanidb.')])
if 'mtime' not in cache or str(int(self.mtime)) != cache.pop('mtime'):
return
- for n, v in cache.iteritems():
+ for n, v in cache.items():
setattr(self, n, v)
self.cached = True
@@ -119,7 +119,7 @@ class Hashthread(threading.Thread):
def hash_files(files, cache = False, algorithms = ('ed2k',), num_threads = 1):
hashlist = []
threads = []
- for x in xrange(num_threads):
+ for x in range(num_threads):
thread = Hashthread(files, hashlist, algorithms, cache)
thread.start()
threads.append(thread)