コード例 #1
0
def _sort_from_lines(fn):
    # sort 'from' order
    replacement_str_pair_list = []
    raw = SafeFile(fn).read_close()
    for import_line in ifilter(lambda line: line.startswith('from '),
                               raw.splitlines()):
        try:
            _from, _source, _import, _what = import_line.split(None, 3)
            assert _from == 'from'
            assert _import == 'import'
            _comment = None
            if '#' in _what:
                _what, _comment = lmap(str.strip, _what.split('#', 1))
            import_list = sorted(imap(str.strip, _what.split(',')))
            new_import_line = 'from %s import %s' % (
                _source, str.join(', ', import_list))
            if _comment is not None:
                new_import_line += '  # ' + _comment
            replacement_str_pair_list.append((import_line, new_import_line))
        except:
            logging.warning('%s: %s', fn, import_line)
            raise
    for (old, new) in replacement_str_pair_list:
        raw = raw.replace(old, new)
    open(fn, 'w').write(raw)
コード例 #2
0
def _sort_import_lines(fn):
    # sort 'import' order
    replacement_str_pair_list = []
    raw = SafeFile(fn).read_close()
    for import_line in ifilter(lambda line: line.startswith('import '),
                               raw.splitlines()):
        import_list = sorted(imap(
            str.strip,
            import_line.replace('import ', '').split(',')),
                             key=lambda x: (len(x), x))
        replacement_str_pair_list.append(
            (import_line, 'import %s' % str.join(', ', import_list)))
    for (old, new) in replacement_str_pair_list:
        raw = raw.replace(old, new)
    open(fn, 'w').write(raw)