howdoi.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/python
  2. ##################################################
  3. #
  4. # howdoi - a unix code search tool.
  5. # written by Benjamin Gleitzman (gleitz@mit.edu)
  6. # inspired by Rich Jones (rich@anomos.info)
  7. #
  8. ##################################################
  9. import urllib
  10. import urllib2
  11. import sys
  12. import json
  13. from BeautifulSoup import BeautifulSoup as bs
  14. SEARCH_URL = "https://www.googleapis.com/customsearch/v1?key=AIzaSyCo6SQ6XNvvS3fdJLcDNR4mpdIGGmVcXAk&cx=015163316206774170098:pj94ujarmcg&q={0}&alt=json"
  15. def get_result(url):
  16. print url
  17. result = urllib2.urlopen(url)
  18. return result.read()
  19. def get_instructions(query):
  20. url = SEARCH_URL.format(urllib.quote(query))
  21. result = get_result(url)
  22. if not result:
  23. return ''
  24. else:
  25. response = json.loads(result)
  26. try:
  27. link = response['items'][0]['link']
  28. page = get_result(link)
  29. soup = bs(page)
  30. return soup.find("div", {"class": "answer"}).find("code").text
  31. except:
  32. return ''
  33. def howdoi(query):
  34. instructions = get_instructions(query) or "Sorry, couldn't find any help with that topic"
  35. print instructions
  36. if __name__ == "__main__":
  37. if len(sys.argv) < 2:
  38. print "USAGE: howdoi query (e.g. howdoi format date bash)"
  39. else:
  40. howdoi(" ".join(sys.argv[1:]))