File: utils.py

package info (click to toggle)
python-seqcluster 1.2.9%2Bds-3
  • links: PTS, VCS
  • area: contrib
  • in suites: bookworm
  • size: 113,624 kB
  • sloc: python: 5,308; makefile: 184; sh: 122; javascript: 55
file content (43 lines) | stat: -rw-r--r-- 869 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""utils from http://www.github.com/chapmanb/bcbio-nextgen.git"""
import os
import shutil

import contextlib

@contextlib.contextmanager
def chdir(p):
    cur_dir =  os.getcwd()
    os.chdir(p)
    try:
        yield
    finally:
        os.chdir(cur_dir)

def safe_dirs(dirs):
    if not os.path.exists(dirs):
        os.makedirs(dirs)
    return dirs

def safe_remove(fn):
    if os.path.exists(fn):
        if os.path.isfile(fn):
            os.remove(fn)
        elif os.path.isdir(fn):
            shutil.rmtree(fn)

@contextlib.contextmanager
def safe_run(fn):
    safe_remove(fn)
    try:
        yield
    except:
        safe_remove(fn)
        raise

def file_exists(fname):
    """Check if a file exists and is non-empty.
    """
    try:
        return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
    except OSError:
        return False