Search DuckDuckGo from the command-line

results.py 992B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import argparse
  2. import json
  3. import os
  4. from beaker.cache import CacheManager
  5. from beaker.util import parse_cache_config_options
  6. from ddg import search
  7. if not os.path.exists('cache'):
  8. os.makedirs('cache')
  9. if not os.path.exists('cache/data'):
  10. os.makedirs('cache/data')
  11. if not os.path.exists('cache/lock'):
  12. os.makedirs('cache/lock')
  13. cache_opts = {
  14. 'cache.type': 'file',
  15. 'cache.data_dir': 'cache/data',
  16. 'cache.lock_dir': 'cache/lock'
  17. }
  18. cache = CacheManager(**parse_cache_config_options(cache_opts))
  19. search_result_cache = cache.get_cache('search-results')
  20. parser = argparse.ArgumentParser(
  21. description='Search duckduckgo and return JSON results'
  22. )
  23. parser.add_argument('query', metavar='Q', type=str,
  24. help='The query to search on duckduckgo')
  25. args = parser.parse_args()
  26. def get_results():
  27. return list(search(args.query, max_results=10))
  28. results = search_result_cache.get(key=args.query, createfunc=get_results)
  29. print(json.dumps(results))