diff options
| -rwxr-xr-x | wikiquery | 78 | 
1 files changed, 52 insertions, 26 deletions
| @@ -1,12 +1,13 @@  #! /usr/bin/env python +import shlex  import optparse  import sys  import wikipedia  from functools import partial -version = "0.0.2" +version = "0.1.1"  def stringify(o):  	if isinstance(o, list): @@ -20,15 +21,59 @@ def stringify(o):  def display(o):  	print stringify(o) + +def search(topic, index): +	results = wikipedia.search(topic) +	if len(results) == 1: +		display(wikipedia.summary(results[0])) +	else: +		if index is not None: +			try: +				display(wikipedia.summary(results[index])) +			except IndexError: +				print "index out of range, options are: [%s]" % stringify(results) +		else: +			display(results) + +def url(topic, index): +	try: +		page = wikipedia.page(topic) +	except wikipedia.exceptions.DisambiguationError as e: +		if index is not None: +			try: +				display(wikipedia.page(e.options[index]).url) +			except IndexError: +				print "index out of range, options are: [%s]" % stringify(e.options) +		else: +			display(e.options) +	else: +		display(page.url) + +def summary(topic, index): +	try: +		display(wikipedia.summary(topic)) +	except wikipedia.exceptions.DisambiguationError as e: +		if index is not None: +			try: +				display(wikipedia.summary(e.options[index])) +			except IndexError: +				print "index out of range, options are: [%s]" % stringify(e.options) +		else: +			display(e.options)  def parse_args(): -	parser = optparse.OptionParser(usage="!wiki <topic> [--search|--url]") +	args = sys.argv[1:] + +	if not args: +		args = sys.stdin.read().splitlines() + +	parser = optparse.OptionParser(usage="!wiki <topic> [index] [--search|--url]")  	parser.add_option("--search", action="store_true")  	parser.add_option("--url", action="store_true")  	parser.add_option("-v", "--version", action="store_true") -	return parser.parse_args() +	return parser.parse_args(args)  def main():  	options, args = parse_args() @@ -42,31 +87,12 @@ def main():  		index = int(args.pop(0)) if args else None  		if options.search: -			results = wikipedia.search(topic) -			if len(results) == 1: -				display(wikipedia.summary(results[0])) -			else: -				if index is not None: -					try: -						display(wikipedia.summary(results[index])) -					except IndexError: -						print "index out of range, options are: [%s]" % stringify(results) -				else: -					display(results) +			search(topic, index)  		elif options.url: -			page = wikipedia.page(topic) -			display(page.url) +			url(topic, index)	  		else: -			try: -				display(wikipedia.summary(topic)) -			except wikipedia.exceptions.DisambiguationError as e: -				if index is not None: -					try: -						display(wikipedia.summary(e.options[index])) -					except IndexError: -						print "index out of range, options are: [%s]" % stringify(e.options) -				else: -					display(e.options) +			summary(topic, index) +  if __name__ == "__main__":  	main() | 
