| 1 |
import os |
| 2 |
import sys |
| 3 |
import subprocess |
| 4 |
import shlex |
| 5 |
|
| 6 |
class Error (Exception): pass |
| 7 |
|
| 8 |
def open_file_read(filename): |
| 9 |
if filename == '-': |
| 10 |
f = sys.stdin |
| 11 |
elif filename.endswith('.gz'): |
| 12 |
# first check that the file is OK according to gunzip |
| 13 |
retcode = subprocess.call('gunzip -t ' + filename, shell=True) |
| 14 |
if retcode != 0: |
| 15 |
raise Error("Error opening for reading gzipped file '" + filename + "'") |
| 16 |
|
| 17 |
# now open the file |
| 18 |
f = os.popen('gunzip -c ' + filename) |
| 19 |
else: |
| 20 |
try: |
| 21 |
f = open(filename) |
| 22 |
except: |
| 23 |
raise Error("Error opening for reading file '" + filename + "'") |
| 24 |
|
| 25 |
return f |
| 26 |
|
| 27 |
|
| 28 |
def open_file_write(filename): |
| 29 |
if filename == '-': |
| 30 |
f = sys.stdout |
| 31 |
elif filename.endswith('.gz'): |
| 32 |
if not os.path.exists(os.path.abspath(os.path.dirname(filename))): |
| 33 |
raise Error("Error opening for writing gzipped file '" + filename + "'") |
| 34 |
|
| 35 |
try: |
| 36 |
f = os.popen('gzip -9 -c > ' + filename, 'w') |
| 37 |
except: |
| 38 |
raise Error("Error opening for writing gzipped file '" + filename + "'") |
| 39 |
else: |
| 40 |
try: |
| 41 |
f = open(filename, 'w') |
| 42 |
except: |
| 43 |
raise Error("Error opening for writing file '" + filename + "'") |
| 44 |
|
| 45 |
return f |
| 46 |
|
| 47 |
|
| 48 |
def close(filehandle): |
| 49 |
if filehandle not in [sys.stdout, sys.stderr]: |
| 50 |
filehandle.close() |
| 51 |
|
| 52 |
|
| 53 |
def file_transpose(f_in, f_out, sep_in=None, sep_out='\t'): |
| 54 |
rows = [] |
| 55 |
f = open_file_read(f_in) |
| 56 |
for line in f: |
| 57 |
rows.append(line.rstrip().split(sep_in)) |
| 58 |
close(f) |
| 59 |
|
| 60 |
columns_out = max([len(x) for x in rows]) |
| 61 |
|
| 62 |
for r in rows: |
| 63 |
r += ['.'] * (columns_out - len(r)) |
| 64 |
|
| 65 |
f = open_file_write(f_out) |
| 66 |
for i in range(columns_out): |
| 67 |
print(sep_out.join([str(rows[x][i]) for x in range(len(rows))]), file=f) |
| 68 |
|
| 69 |
close(f) |
| 70 |
|
| 71 |
|
| 72 |
def syscall(cmd): |
| 73 |
retcode = subprocess.call(cmd, shell=True) |
| 74 |
|
| 75 |
if retcode != 0: |
| 76 |
raise Error("Error in system call. Command was:\n" + cmd) |
| 77 |
|
| 78 |
|
| 79 |
def syscall_get_stdout(cmd): |
| 80 |
try: |
| 81 |
out = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE).communicate()[0].decode('utf-8').rstrip() |
| 82 |
return out.split('\n') |
| 83 |
except: |
| 84 |
raise Error('Error in system call. I tried to run:\n' + str(cmd)) |
| 85 |
|
| 86 |
|