Skip to content

Instantly share code, notes, and snippets.

@jannismain
Forked from koji-kojiro/import_from_gist.py
Last active May 14, 2020 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jannismain/ecf78c00428067ec9289db9007c3f58b to your computer and use it in GitHub Desktop.
Save jannismain/ecf78c00428067ec9289db9007c3f58b to your computer and use it in GitHub Desktop.
[Python] import from Gist
#!/usr/bin/env python3
def load_gist(gist_id):
"""translate Gist ID to URL"""
from json import load
from urllib.request import urlopen
gist_api = urlopen("https://api.github.com/gists/" + gist_id)
files = load(gist_api)["files"]
files_head_member = list(files.keys())[0]
raw_url = files[files_head_member]["raw_url"]
gist_src = urlopen(raw_url).read().decode()
return gist_src
def import_from_gist(gist_id):
"""import from Gist"""
from sys import path
from tempfile import mkdtemp
from importlib import import_module
gist_src = load_gist(gist_id)
temp_dir = mkdtemp()
mod_name = f'module_{gist_id}'
path.append(temp_dir)
with open(temp_dir + "/" + mod_name + ".py", "w") as f:
f.write(gist_src)
mod = import_module(mod_name)
return mod
if __name__ == "__main__":
gist_id = "55b8bec6e652c860f287288d98bc507f"
mod = import_from_gist(gist_id)
mod.hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment