open_atmos_jupyter_utils.temporary_file
1# pylint: disable=missing-module-docstring 2 3import os 4import sys 5import tempfile 6from ipywidgets import HTML, Button 7from IPython.display import FileLink 8 9if 'google.colab' in sys.modules: 10 # pylint: disable-next=import-error 11 from google import colab 12 ABSOLUTE_PATH = '/content' 13else: 14 ABSOLUTE_PATH = os.getcwd() 15 RELATIVE_PATH = '.' 16 17 18class TemporaryFile: 19 """ Jupyter-friendly temporary files with Colab-compatible download-link generation """ 20 21 def __init__(self, suffix='.pdf', filename=None): 22 if filename is None: 23 _, self.absolute_path = tempfile.mkstemp( 24 dir=ABSOLUTE_PATH, 25 suffix=suffix 26 ) 27 else: 28 self.absolute_path = os.path.join(ABSOLUTE_PATH, filename) 29 self.basename = os.path.basename(self.absolute_path) 30 31 def __str__(self): 32 return self.absolute_path 33 34 def make_link_widget(self): 35 """ returns a click-to-download widget to be display()-ed in a Jupyter notebook """ 36 if 'google.colab' in sys.modules: 37 link = Button(description=self.basename) 38 link.on_click(lambda _: colab.files.download(self.absolute_path)) 39 else: 40 link = HTML() 41 filename = str(os.path.join(RELATIVE_PATH, self.basename)) 42 # pylint: disable-next=protected-access 43 link.value = FileLink(filename)._format_path() 44 return link
class
TemporaryFile:
19class TemporaryFile: 20 """ Jupyter-friendly temporary files with Colab-compatible download-link generation """ 21 22 def __init__(self, suffix='.pdf', filename=None): 23 if filename is None: 24 _, self.absolute_path = tempfile.mkstemp( 25 dir=ABSOLUTE_PATH, 26 suffix=suffix 27 ) 28 else: 29 self.absolute_path = os.path.join(ABSOLUTE_PATH, filename) 30 self.basename = os.path.basename(self.absolute_path) 31 32 def __str__(self): 33 return self.absolute_path 34 35 def make_link_widget(self): 36 """ returns a click-to-download widget to be display()-ed in a Jupyter notebook """ 37 if 'google.colab' in sys.modules: 38 link = Button(description=self.basename) 39 link.on_click(lambda _: colab.files.download(self.absolute_path)) 40 else: 41 link = HTML() 42 filename = str(os.path.join(RELATIVE_PATH, self.basename)) 43 # pylint: disable-next=protected-access 44 link.value = FileLink(filename)._format_path() 45 return link
Jupyter-friendly temporary files with Colab-compatible download-link generation
def
make_link_widget(self):
35 def make_link_widget(self): 36 """ returns a click-to-download widget to be display()-ed in a Jupyter notebook """ 37 if 'google.colab' in sys.modules: 38 link = Button(description=self.basename) 39 link.on_click(lambda _: colab.files.download(self.absolute_path)) 40 else: 41 link = HTML() 42 filename = str(os.path.join(RELATIVE_PATH, self.basename)) 43 # pylint: disable-next=protected-access 44 link.value = FileLink(filename)._format_path() 45 return link
returns a click-to-download widget to be display()-ed in a Jupyter notebook