|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from IPython.core.interactiveshell import InteractiveShell |
| 6 | +from IPython.core.magic import line_magic |
| 7 | +from IPython.core.magic import Magics |
| 8 | +from IPython.core.magic import magics_class |
| 9 | +from IPython.core.magic import needs_local_scope |
| 10 | +from IPython.core.magic import no_var_expand |
| 11 | +from jinja2 import Template |
| 12 | + |
| 13 | + |
| 14 | +@magics_class |
| 15 | +class RunPersonalMagic(Magics): |
| 16 | + def __init__(self, shell: InteractiveShell): |
| 17 | + Magics.__init__(self, shell=shell) |
| 18 | + |
| 19 | + @no_var_expand |
| 20 | + @needs_local_scope |
| 21 | + @line_magic('run_personal') |
| 22 | + def run_personal(self, line: str, local_ns: Any = None) -> Any: |
| 23 | + """ |
| 24 | + Downloads a personal file using the %sql magic and then runs it using %run. |
| 25 | +
|
| 26 | + Examples:: |
| 27 | +
|
| 28 | + # Line usage |
| 29 | +
|
| 30 | + %run_personal personal_file.ipynb |
| 31 | +
|
| 32 | + %run_personal {{ sample_notebook_name }} |
| 33 | +
|
| 34 | + """ |
| 35 | + |
| 36 | + template = Template(line.strip()) |
| 37 | + personal_file = template.render(local_ns) |
| 38 | + if not personal_file: |
| 39 | + raise ValueError('No personal file specified.') |
| 40 | + if (personal_file.startswith("'") and personal_file.endswith("'")) or \ |
| 41 | + (personal_file.startswith('"') and personal_file.endswith('"')): |
| 42 | + personal_file = personal_file[1:-1] |
| 43 | + if not personal_file: |
| 44 | + raise ValueError('No personal file specified.') |
| 45 | + |
| 46 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 47 | + temp_file_path = os.path.join(temp_dir, personal_file) |
| 48 | + sql_command = ( |
| 49 | + f"DOWNLOAD PERSONAL FILE '{personal_file}' " |
| 50 | + f"TO '{temp_file_path}'" |
| 51 | + ) |
| 52 | + |
| 53 | + # Execute the SQL command |
| 54 | + self.shell.run_line_magic('sql', sql_command) |
| 55 | + # Run the downloaded file |
| 56 | + self.shell.run_line_magic('run', f'"{temp_file_path}"') |
0 commit comments