Skip to content

Instantly share code, notes, and snippets.

@smutch
Last active May 18, 2016 02:44
Show Gist options
  • Save smutch/2b0cd2b4b387995f319479a50bfa44fe to your computer and use it in GitHub Desktop.
Save smutch/2b0cd2b4b387995f319479a50bfa44fe to your computer and use it in GitHub Desktop.
py: ADS tools
#!/usr/bin/env python3
"""ADS tools."""
from requests import post
from pathlib import Path
import subprocess
import click
import webbrowser
from urllib.parse import quote as url_quote
__author__ = "Simon Mutch"
__date__ = "2016-04-26"
def write_to_clipboard(output):
"""http://stackoverflow.com/a/25802742 ."""
process = subprocess.Popen(
'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
def generate_header():
"""Generate a POST header using API key."""
with Path("~/.ads/dev_key").expanduser().open('r') as fd:
token = fd.readline().strip()
return {'Authorization': 'Bearer '+token}
@click.group('cli')
def cli():
pass
@cli.command()
@click.argument('id', type=click.STRING)
def bibtex(id):
"""Convert an ADS identifier to a bibtex record."""
data = {"bibcode": [id]}
header = generate_header()
r = post("https://api.adsabs.harvard.edu/v1/export/bibtex", data=data,
headers=header)
bib_entry = r.json()['export']
print(bib_entry)
write_to_clipboard(bib_entry)
@cli.command()
@click.argument('query', type=click.STRING)
def search(query):
query = query.replace('a:', 'author:').replace('y:', 'year:')
url = 'https://ui.adsabs.harvard.edu/#search/q='+url_quote(query)\
+ '&sort='+url_quote('date desc')
webbrowser.open_new_tab(url)
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment