2013-12-16 17:20:40 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2013-12-16 20:08:28 +00:00
|
|
|
from __future__ import print_function
|
2013-12-16 17:20:40 +00:00
|
|
|
|
2013-12-17 02:27:41 +00:00
|
|
|
from collections import Iterable
|
2013-12-16 22:13:45 +00:00
|
|
|
import errno
|
2013-12-17 02:27:41 +00:00
|
|
|
from itertools import islice
|
2013-12-16 20:08:28 +00:00
|
|
|
import os
|
2013-12-16 17:20:40 +00:00
|
|
|
import platform
|
2013-12-16 22:13:45 +00:00
|
|
|
import shutil
|
2013-12-16 17:20:40 +00:00
|
|
|
import sys
|
|
|
|
|
|
|
|
|
2013-12-16 20:08:28 +00:00
|
|
|
def create_dir(path):
|
|
|
|
"""Creates a directory atomically."""
|
|
|
|
try:
|
|
|
|
os.makedirs(path)
|
|
|
|
except OSError as exception:
|
|
|
|
if exception.errno != errno.EEXIST:
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
2013-12-16 21:39:49 +00:00
|
|
|
def decode(string):
|
|
|
|
"""Converts byte string to Unicode string."""
|
|
|
|
if is_python2():
|
|
|
|
return string.decode('utf-8', errors='replace')
|
|
|
|
return string
|
|
|
|
|
|
|
|
|
|
|
|
def encode(string):
|
|
|
|
"""Converts Unicode string to byte string."""
|
|
|
|
if is_python2():
|
|
|
|
return string.encode('utf-8', errors='replace')
|
|
|
|
return string
|
|
|
|
|
|
|
|
|
|
|
|
def encode_local(string, encoding=None):
|
|
|
|
"""Converts string into local filesystem encoding."""
|
|
|
|
if is_python2():
|
|
|
|
return decode(string).encode(encoding or sys.getfilesystemencoding())
|
|
|
|
return string
|
|
|
|
|
|
|
|
|
2013-12-17 02:27:41 +00:00
|
|
|
def first(xs):
|
|
|
|
it = iter(xs)
|
|
|
|
try:
|
|
|
|
return it.next()
|
|
|
|
except StopIteration:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2013-12-16 21:39:49 +00:00
|
|
|
def is_python2():
|
|
|
|
return sys.version_info[0] == 2
|
|
|
|
|
|
|
|
|
2013-12-16 17:20:40 +00:00
|
|
|
def is_linux():
|
|
|
|
return platform.system() == 'Linux'
|
|
|
|
|
|
|
|
|
|
|
|
def is_osx():
|
|
|
|
return platform.system() == 'Darwin'
|
|
|
|
|
|
|
|
|
2013-12-16 20:08:28 +00:00
|
|
|
def is_windows():
|
|
|
|
return platform.system() == 'Windows'
|
|
|
|
|
|
|
|
|
|
|
|
def move_file(src, dst):
|
|
|
|
"""
|
|
|
|
Atomically move file.
|
|
|
|
|
|
|
|
Windows does not allow for atomic file renaming (which is used by
|
|
|
|
os.rename / shutil.move) so destination paths must first be deleted.
|
|
|
|
"""
|
|
|
|
if is_windows() and os.path.exists(dst):
|
|
|
|
# raises exception if file is in use on Windows
|
|
|
|
os.remove(dst)
|
|
|
|
shutil.move(src, dst)
|
2013-12-16 22:54:27 +00:00
|
|
|
|
|
|
|
|
2013-12-17 02:27:41 +00:00
|
|
|
def print_entry(path, weight):
|
2013-12-16 22:54:27 +00:00
|
|
|
print(encode_local("%.1f:\t%s" % (weight, path)))
|
2013-12-17 02:27:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
def take(n, iterable):
|
|
|
|
"""Return first n items of an iterable."""
|
|
|
|
return islice(iterable, n)
|