Skip to content

Instantly share code, notes, and snippets.

@nvictus
Last active February 27, 2023 23:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvictus/1f71d7e861ee3396f0982532740aff46 to your computer and use it in GitHub Desktop.
Save nvictus/1f71d7e861ee3396f0982532740aff46 to your computer and use it in GitHub Desktop.
Fetch reference citations in BibTeX, JSON or YAML from DOI
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import tempfile
import requests
import argparse
import textwrap
import sys
def main(doi, format):
"""
Fetch a citation from a DOI using the doi.org service.
Prints either BibTeX, JSON or YAML to stdout.
Requires
--------
* requests package for Python
* pandoc, pandoc-citeproc for JSON or YAML output
"""
if args['doi'].startswith('http://'):
url = args['doi']
elif args['doi'].startswith('dx.doi.org') or args['doi'].startswith('doi.org'):
url = 'http://' + args['doi']
else:
url = 'http://doi.org/' + args['doi']
with tempfile.NamedTemporaryFile(suffix='.bib') as f:
# Fetch BibTeX from dx.doi.org
r = requests.get(
url,
headers={'Accept': 'text/bibliography; style=bibtex'})
r.raise_for_status()
f.write(r.content)
f.seek(0)
# Convert to JSON or YAML
if args['format'] in ('json', 'yaml'):
cmd = ['pandoc-citeproc', '--bib2' + args['format'], f.name]
subprocess.run(cmd, stdout=sys.stdout)
else:
stdout = getattr(sys.stdout, 'buffer', sys.stdout)
stdout.write(f.read())
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=textwrap.dedent(main.__doc__),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'doi',
type=str,
help="DOI or http://doi.org URL")
parser.add_argument(
'--format', '-f',
default='bib',
choices=['bib', 'json', 'yaml'],
help="Output format (default: bib)")
args = vars(parser.parse_args())
main(**args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment