0
+ − 1 __author__ = 'cbarnett'
+ − 2 __license__ = "MIT"
1
+ − 3 __version = "0.3.1"
0
+ − 4 # http://www.kegg.jp/kegg/rest/keggapi.html
+ − 5
+ − 6
+ − 7 def linked_entries_from_kegg(targetdb="glycan", sourcedb="pathway"):
+ − 8 """
+ − 9 :param targetdb:
+ − 10 :param sourcedb:
+ − 11 :return: string of linked entries
+ − 12 """
+ − 13 import urllib2
+ − 14
+ − 15 uri = 'http://rest.kegg.jp/link/'
1
+ − 16
+ − 17 import re
+ − 18 p = re.compile(' *\+ *') # ensure no unneccessary space in an AND query
+ − 19 sdbfix = p.subn('+', sourcedb)
+ − 20 sourcedb=sdbfix[0]
+ − 21
+ − 22 if ' ' in sourcedb:
+ − 23 sourcedb = sourcedb.replace(' ', '%20') # previous behaviour was ignoring text after a space, rather convert to '%20' and pass on to KEGG REST service
+ − 24
0
+ − 25 fulluri = uri + targetdb + "/" + sourcedb
+ − 26 try:
+ − 27 response = urllib2.urlopen(fulluri).read()
+ − 28 except Exception as e:
+ − 29 raise urllib2.HTTPError(e.url, e.code, e.msg, e.hdrs, e.fp)
+ − 30 if str(response.strip()) == "":
+ − 31 return ""
+ − 32 return response
+ − 33
+ − 34
+ − 35 if __name__ == "__main__":
+ − 36 from optparse import OptionParser
+ − 37
+ − 38 usage = "usage: python %prog [options]\n"
+ − 39 parser = OptionParser(usage=usage)
+ − 40 parser.add_option("-t", action="store", type="string", dest="t", default="glycan",
+ − 41 help="target db name pathway | brite | module | ko | genome | <org> | compound | glycan | reaction | rpair | rclass | enzyme | disease | drug | dgroup | environ")
+ − 42 parser.add_option("-s", action="store", type="string", dest="s", default="pathway",
+ − 43 help="source db name or db entry e.g. map00010")
+ − 44 parser.add_option("-o", action="store", type="string", dest="o", default="linked_entries.txt",
+ − 45 help="linked entries output in text format")
+ − 46 (options, args) = parser.parse_args()
+ − 47 try:
+ − 48 outstream = file(options.o, 'w')
+ − 49 except Exception as e:
+ − 50 raise IOError(e, "the output file cannot be opened. Use -h flag for help")
+ − 51 linked = linked_entries_from_kegg(targetdb=options.t, sourcedb=options.s)
+ − 52 try:
+ − 53 outstream.write(linked)
+ − 54 except Exception as e:
+ − 55 raise IOError(e, "cannot open output files. -h flag for help")
+ − 56 finally:
+ − 57 outstream.close()
+ − 58
+ − 59