import bioblend
from bioblend.galaxy import GalaxyInstance
import os
import subprocess
galaxy_server = 'http://galaxy.server.net/' # galaxy server url OR IP
galaxy_web_api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # your galaxy web api key; DO NOT SHARE!
history_name = "my history" # your history name
outdir = os.getcwd()
########################################################################
def show_attributes(obj):
"""
Prints key-value pairs of every attribute.
"""
for key in sorted(obj.keys()):
print key, ":", obj[key]
print
########################################################################
gi = GalaxyInstance(galaxy_server, key=galaxy_web_api_key)
## History
h = gi.histories.get_histories(name=history_name)[0]
print "# History", "#"*48
print h['name']
print h['id']
##show_attributes(h)
print
## Dataset
i = 0
datasets = gi.histories.show_matching_datasets(h['id'])
for d in datasets:
i += 1
print "## Dataset", i, "of", len(datasets), "#"*40
print d['name']
print d['id']
print d['misc_blurb']
#show_attributes(d)
outfile = os.path.join(outdir,d['name']+".gz")
if os.path.isfile(outfile):
print "File already exists:", outfile
continue
## Download
print "downloading..."
download = gi.histories.download_dataset(h['id'], d['id'], file_path=outdir)
print download
## gzip fastq
if os.path.isfile(download) and download.endswith("fastq"):
print "gzip..."
subprocess.check_call("gzip -1 < {} > {}".format(download, outfile), shell=True)
if os.path.isfile(outfile):
print outfile
try:
os.remove(download)
except:
pass
else:
print "Error! File from download does NOT exist!"
print download
exit(1)
print