|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Dataproc magic implementations.""" |
| 16 | + |
| 17 | +import shlex |
| 18 | +from IPython.core.magic import (Magics, magics_class, line_magic) |
| 19 | +from google.cloud.dataproc_spark_connect import DataprocSparkSession |
| 20 | + |
| 21 | + |
| 22 | +@magics_class |
| 23 | +class DataprocMagics(Magics): |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + shell, |
| 28 | + **kwargs, |
| 29 | + ): |
| 30 | + super().__init__(shell, **kwargs) |
| 31 | + |
| 32 | + def _parse_command(self, args): |
| 33 | + if not args or args[0] != "install": |
| 34 | + print("Usage: %dp_spark_pip install <package1> <package2> ...") |
| 35 | + return |
| 36 | + |
| 37 | + # filter out 'install' and the flags (not currently supported) |
| 38 | + packages = [pkg for pkg in args[1:] if not pkg.startswith("-")] |
| 39 | + return packages |
| 40 | + |
| 41 | + @line_magic |
| 42 | + def dp_spark_pip(self, line): |
| 43 | + """ |
| 44 | + Custom magic to install pip packages as Spark Connect artifacts. |
| 45 | + Usage: %dp_spark_pip install pandas numpy |
| 46 | + """ |
| 47 | + try: |
| 48 | + packages = self._parse_command(shlex.split(line)) |
| 49 | + |
| 50 | + if not packages: |
| 51 | + print("No packages specified.") |
| 52 | + return |
| 53 | + |
| 54 | + sessions = [ |
| 55 | + obj |
| 56 | + for obj in self.shell.user_ns.values() |
| 57 | + if isinstance(obj, DataprocSparkSession) |
| 58 | + ] |
| 59 | + |
| 60 | + if not sessions: |
| 61 | + print( |
| 62 | + "No active Spark Sessions found. Please create one first." |
| 63 | + ) |
| 64 | + return |
| 65 | + |
| 66 | + print("Installing packages: %s", packages) |
| 67 | + for session in sessions: |
| 68 | + for package in packages: |
| 69 | + session.addArtifacts(package, pypi=True) |
| 70 | + |
| 71 | + print("Packages successfully added as artifacts.") |
| 72 | + except Exception as e: |
| 73 | + print(f"Failed to add artifacts: {e}") |
0 commit comments