使用 Databricks 实用工具 ( dbutils ) 可以轻松地执行各种强大的任务组合。 可以使用这些实用工具来有效地处理对象存储,对笔记本进行链接和参数化,以及处理机密。 对 dbutils 的支持仅限于笔记本内。

在执行器内调用 dbutils 可能会产生意外的结果。 若要详细了解 dbutils 的限制和可改用的替代方法,请参阅 dbutils

dbutils 实用工具在 Python、R 和 Scala 笔记本中可用。

如何: 列出实用工具 列出命令 显示命令帮助

实用工具: 数据 fs 作业 笔记本 机密 小组件 实用工具 API 库

列出可用的实用工具

要列出可用的实用工具以及每个实用工具的简短说明,请针对 Python 或 Scala 运行 dbutils.help()

此示例列出了 Databricks 实用工具的可用命令。

Python

dbutils.help()

Scala

dbutils.help()
This module provides various utilities for users to interact with the rest of Databricks.
fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the console
jobs: JobsUtils -> Utilities for leveraging jobs features
library: LibraryUtils -> Utilities for session isolated libraries
notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)
secrets: SecretUtils -> Provides utilities for leveraging secrets within notebooks
widgets: WidgetsUtils -> Methods to create and get bound value of input widgets inside notebooks

列出实用工具的可用命令

要列出实用工具的可用命令以及每个命令的简短说明,请在此实用工具的编程名称之后运行 .help()

此示例列出了 Databricks 文件系统 (DBFS) 实用工具的可用命令。

Python

dbutils.fs.help()
dbutils.fs.help()

Scala

dbutils.fs.help()
dbutils.fs provides utilities for working with FileSystems. Most methods in this package can take either a DBFS path (e.g., "/foo" or "dbfs:/foo"), or another FileSystem URI. For more info about a method, use dbutils.fs.help("methodName"). In notebooks, you can also use the %fs shorthand to access DBFS. The %fs shorthand maps straightforwardly onto dbutils calls. For example, "%fs head --maxBytes=10000 /file/path" translates into "dbutils.fs.head("/file/path", maxBytes = 10000)".
fsutils
cp(from: String, to: String, recurse: boolean = false): boolean -> Copies a file or directory, possibly across FileSystems
head(file: String, maxBytes: int = 65536): String -> Returns up to the first 'maxBytes' bytes of the given file as a String encoded in UTF-8
ls(dir: String): Seq -> Lists the contents of a directory
mkdirs(dir: String): boolean -> Creates the given directory if it does not exist, also creating any necessary parent directories
mv(from: String, to: String, recurse: boolean = false): boolean -> Moves a file or directory, possibly across FileSystems
put(file: String, contents: String, overwrite: boolean = false): boolean -> Writes the given String out to a file, encoded in UTF-8
rm(dir: String, recurse: boolean = false): boolean -> Removes a file or directory
mount
mount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Mounts the given source directory into DBFS at the given mount point
mounts: Seq -> Displays information about what is mounted within DBFS
refreshMounts: boolean -> Forces all machines in this cluster to refresh their mount cache, ensuring they receive the most recent information
unmount(mountPoint: String): boolean -> Deletes a DBFS mount point
updateMount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Similar to mount(), but updates an existing mount point instead of creating a new one

显示命令的相关帮助

要显示命令的相关帮助,请在命令名称之后运行 .help("<command-name>")

此示例显示 DBFS 复制命令的相关帮助。

Python

dbutils.fs.help("cp")
dbutils.fs.help("cp")

Scala

dbutils.fs.help("cp")
* Copies a file or directory, possibly across FileSystems.
* Example: cp("/mnt/my-folder/a", "dbfs:/a/b")
* @param from FileSystem URI of the source file or directory
* @param to FileSystem URI of the destination file or directory
* @param recurse if true, all files and directories will be recursively copied
* @return true if all files were successfully copied
cp(from: java.lang.String, to: java.lang.String, recurse: boolean = false): boolean

数据实用工具 (dbutils.data)

此功能目前以公共预览版提供。

可在 Databricks Runtime 9.0 及更高版本中使用。

命令:summarize

使用数据实用工具可以理解和解释数据集。 要列出可用命令,请运行 dbutils.data.help()

dbutils.data provides utilities for understanding and interpreting datasets. This module is currently in preview and may be unstable. For more info about a method, use dbutils.data.help("methodName").
summarize(df: Object, precise: boolean): void -> Summarize a Spark DataFrame and visualize the statistics to get quick insights

summarize 命令 (dbutils.data.summarize)

计算并显示 Apache Spark DataFrame 或 pandas DataFrame 的摘要统计信息。 此命令可用于 Python、Scala 和 R。

要显示此命令的相关帮助,请运行 dbutils.data.help("summarize")

在 Databricks Runtime 10.1 及更高版本中,可以使用其他 precise 参数来调整计算统计信息的精度。

此功能目前以公共预览版提供。

  • 如果将 precise 设置为 false(默认值),则某些返回的统计信息会包含近似值以缩短运行时间。
  • 对于高基数列,分类列的非重复值数目可能存在大约 5% 的相对错误。
  • 如果非重复值数目大于 10000,则频繁值计数可能最多出现 0.01% 的错误。
  • 相对于总行数,直方图和百分位估计值可能最多出现 0.01% 的错误。
  • 如果将 precise 设置为 true,计算的统计信息具有更高的精度。 对于数值列,除直方图和百分位估计值以外的所有统计信息目前都非常精确。
  • 相对于总行数,直方图和百分位估计值可能最多出现 0.0001% 的错误。
  • 数据摘要输出顶部的工具提示指示当前运行模式。

    此示例显示默认启用了近似值的 Apache Spark DataFrame 的摘要统计信息。 要查看结果,请在笔记本中运行此命令。 此示例基于示例数据集

    Python

    df = spark.read.format('csv').load(
      '/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv',
      header=True,
      inferSchema=True
    dbutils.data.summarize(df)
    
    df <- read.df("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", source = "csv", header="true", inferSchema = "true")
    dbutils.data.summarize(df)
    

    Scala

    val df = spark.read.format("csv")
      .option("inferSchema", "true")
      .option("header", "true")
      .load("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv")
    dbutils.data.summarize(df)
    

    请注意,可视化效果使用 SI 表示法来简洁地呈现小于 0.01 或大于 10000 的数字值。 例如,数字值 1.25e-15 将呈现为 1.25f。 一个例外:对于 1.0e9千兆),可视化效果为使用“B”而不是“G”。

    文件系统实用工具 (dbutils.fs)

    所有 dbutils.fs 方法的 Python 实现都使用 snake_case 而不是 camelCase 进行关键字格式设置。

    例如:虽然 dbuitls.fs.help() 显示了 dbutils.fs.mount() 的选项 extraConfigs,但在 Python 中,你会使用关键字 extra_configs

    命令:cpheadlsmkdirsmountmountsmvputrefreshMountsrmunmountupdateMount

    文件系统实用工具允许访问什么是 Databricks 文件系统 (DBFS)?,让你可以更轻松地将 Azure Databricks 用作文件系统。 要列出可用命令,请运行 dbutils.fs.help()

    dbutils.fs provides utilities for working with FileSystems. Most methods in this package can take either a DBFS path (e.g., "/foo" or "dbfs:/foo"), or another FileSystem URI. For more info about a method, use dbutils.fs.help("methodName"). In notebooks, you can also use the %fs shorthand to access DBFS. The %fs shorthand maps straightforwardly onto dbutils calls. For example, "%fs head --maxBytes=10000 /file/path" translates into "dbutils.fs.head("/file/path", maxBytes = 10000)".
    fsutils
    cp(from: String, to: String, recurse: boolean = false): boolean -> Copies a file or directory, possibly across FileSystems
    head(file: String, maxBytes: int = 65536): String -> Returns up to the first 'maxBytes' bytes of the given file as a String encoded in UTF-8
    ls(dir: String): Seq -> Lists the contents of a directory
    mkdirs(dir: String): boolean -> Creates the given directory if it does not exist, also creating any necessary parent directories
    mv(from: String, to: String, recurse: boolean = false): boolean -> Moves a file or directory, possibly across FileSystems
    put(file: String, contents: String, overwrite: boolean = false): boolean -> Writes the given String out to a file, encoded in UTF-8
    rm(dir: String, recurse: boolean = false): boolean -> Removes a file or directory
    mount
    mount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Mounts the given source directory into DBFS at the given mount point
    mounts: Seq -> Displays information about what is mounted within DBFS
    refreshMounts: boolean -> Forces all machines in this cluster to refresh their mount cache, ensuring they receive the most recent information
    unmount(mountPoint: String): boolean -> Deletes a DBFS mount point
    updateMount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Similar to mount(), but updates an existing mount point instead of creating a new one
    

    cp 命令 (dbutils.fs.cp)

    复制文件或目录,可能跨文件系统复制。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("cp")

    此示例将名为 old_file.txt 的文件从 /FileStore 复制到 /tmp/new,将复制的文件重命名为 new_file.txt

    Python

    dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")
    # Out[4]: True
    
    dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")
    # [1] TRUE
    

    Scala

    dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")
    // res3: Boolean = true
    

    head 命令 (dbutils.fs.head)

    最多返回给定文件的指定最大字节数。 字节以 UTF-8 编码字符串形式返回。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("head")

    此示例显示位于 /tmp 中的 my_file.txt 文件的前 25 个字节。

    Python

    dbutils.fs.head("/tmp/my_file.txt", 25)
    # [Truncated to first 25 bytes]
    # Out[12]: 'Apache Spark is awesome!\n'
    
    dbutils.fs.head("/tmp/my_file.txt", 25)
    # [1] "Apache Spark is awesome!\n"
    

    Scala

    dbutils.fs.head("/tmp/my_file.txt", 25)
    // [Truncated to first 25 bytes]
    // res4: String =
    // "Apache Spark is awesome!
    

    ls 命令 (dbutils.fs.ls)

    列出目录的内容。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("ls")

    此示例显示有关 /tmp 的内容的信息。 modificationTime 字段适用于 Databricks Runtime 10.2 和更高版本。 在 R 中, modificationTime 作为字符串返回。

    Python

    dbutils.fs.ls("/tmp")
    # Out[13]: [FileInfo(path='dbfs:/tmp/my_file.txt', name='my_file.txt', size=40, modificationTime=1622054945000)]
    
    dbutils.fs.ls("/tmp")
    # For prettier results from dbutils.fs.ls(<dir>), please use `%fs ls <dir>`
    # [[1]]
    # [[1]]$path
    # [1] "dbfs:/tmp/my_file.txt"
    # [[1]]$name
    # [1] "my_file.txt"
    # [[1]]$size
    # [1] 40
    # [[1]]$isDir
    # [1] FALSE
    # [[1]]$isFile
    # [1] TRUE
    # [[1]]$modificationTime
    # [1] "1622054945000"
    

    Scala

    dbutils.fs.ls("/tmp")
    // res6: Seq[com.databricks.backend.daemon.dbutils.FileInfo] = WrappedArray(FileInfo(dbfs:/tmp/my_file.txt, my_file.txt, 40, 1622054945000))
    

    mkdirs 命令 (dbutils.fs.mkdirs)

    如果给定目录不存在,则创建它。 同时创建任何必要的父目录。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("mkdirs")

    此示例在 /tmp 内创建目录结构 /parent/child/grandchild

    Python

    dbutils.fs.mkdirs("/tmp/parent/child/grandchild")
    # Out[15]: True
    
    dbutils.fs.mkdirs("/tmp/parent/child/grandchild")
    # [1] TRUE
    

    Scala

    dbutils.fs.mkdirs("/tmp/parent/child/grandchild")
    // res7: Boolean = true
    

    mount 命令 (dbutils.fs.mount)

    将指定的源目录装载到 DBFS 中的指定装入点。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("mount")

    Python

    dbutils.fs.mount(
      source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net",
      mount_point = "/mnt/<mount-name>",
      extra_configs = {"<conf-key>":dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")})
    

    Scala

    dbutils.fs.mount(
      source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/<directory-name>",
      mountPoint = "/mnt/<mount-name>",
      extraConfigs = Map("<conf-key>" -> dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")))
    

    有关其他代码示例,请参阅访问 Azure Data Lake Storage Gen2 和 Blob 存储

    mounts 命令 (dbutils.fs.mounts)

    显示有关 DBFS 中当前装载内容的信息。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("mounts")

    Python

    dbutils.fs.mounts()
    

    Scala

    dbutils.fs.mounts()
    

    有关其他代码示例,请参阅访问 Azure Data Lake Storage Gen2 和 Blob 存储

    mv 命令 (dbutils.fs.mv)

    移动文件或目录,可能跨文件系统移动。 移动是复制后再删除,即使在文件系统内移动时也一样。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("mv")

    此示例将文件 my_file.txt/FileStore 移动到 /tmp/parent/child/granchild

    Python

    dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")
    # Out[2]: True
    
    dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")
    # [1] TRUE
    

    Scala

    dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")
    // res1: Boolean = true
    

    put 命令 (dbutils.fs.put)

    将指定的字符串写入文件。 该字符串采用 UTF-8 编码。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("put")

    此示例将字符串 Hello, Databricks! 写入 /tmp 中名为 hello_db.txt 的文件。 如果此文件已存在,则会将其覆盖。

    Python

    dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", True)
    # Wrote 18 bytes.
    # Out[6]: True
    
    dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", TRUE)
    # [1] TRUE
    

    Scala

    dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", true)
    // Wrote 18 bytes.
    // res2: Boolean = true
    

    refreshMounts 命令 (dbutils.fs.refreshMounts)

    强制群集中的所有计算机刷新其装载缓存,确保它们能接收最新的信息。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("refreshMounts")

    Python

    dbutils.fs.refreshMounts()
    

    Scala

    dbutils.fs.refreshMounts()
    

    有关其他代码示例,请参阅访问 Azure Data Lake Storage Gen2 和 Blob 存储

    rm 命令 (dbutils.fs.mv)

    移动文件或目录。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("rm")

    此示例删除 /tmp 中名为 hello_db.txt 的文件。

    Python

    dbutils.fs.rm("/tmp/hello_db.txt")
    # Out[8]: True
    
    dbutils.fs.rm("/tmp/hello_db.txt")
    # [1] TRUE
    

    Scala

    dbutils.fs.rm("/tmp/hello_db.txt")
    // res6: Boolean = true
    

    unmount 命令 (dbutils.fs.unmount)

    删除 DBFS 装入点。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("unmount")

    dbutils.fs.unmount("/mnt/<mount-name>")
    

    有关其他代码示例,请参阅访问 Azure Data Lake Storage Gen2 和 Blob 存储

    updateMount 命令 (dbutils.fs.updateMount)

    类似于 dbutils.fs.mount 命令,但更新现有安装点而不是创建新安装点。 如果装入点不存在,则返回错误。

    要显示此命令的相关帮助,请运行 dbutils.fs.help("updateMount")

    此命令在 Databricks Runtime 10.2 和更高版本中可用。

    Python

    dbutils.fs.updateMount(
      source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net",
      mount_point = "/mnt/<mount-name>",
      extra_configs = {"<conf-key>":dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")})
    

    Scala

    dbutils.fs.updateMount(
      source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/<directory-name>",
      mountPoint = "/mnt/<mount-name>",
      extraConfigs = Map("<conf-key>" -> dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")))
    

    作业实用工具 (dbutils.jobs)

    子实用工具:taskValues

    在 Databricks Runtime 7.3 及更高版本中可用。

    此实用工具只适用于 Python。

    作业实用工具允许利用作业功能。 要显示此实用工具的相关帮助,请运行 dbutils.jobs.help()

    Provides utilities for leveraging jobs features.
    taskValues: TaskValuesUtils -> Provides utilities for leveraging job task values
    

    taskValues 子实用工具 (dbutils.jobs.taskValues)

    命令:getset

    在 Databricks Runtime 7.3 及更高版本中可用。

    此子实用工具只适用于 Python。

    提供用于利用作业任务值的命令。

    使用此子实用工具在作业运行过程中设置和获取任意值。 这些值称为“任务值”。 可在同一作业运行中访问下游任务中的任务值。 例如,可以在作业运行中的不同任务之间传递标识符或指标,例如有关机器学习模型评估的信息。 每个任务都可以设置多个任务值或/和获取这些值。 每个任务值在同一个任务中都具有一个唯一的键。 此唯一键称为任务值的键。 使用任务名称和任务值的键访问任务值。

    要显示此子实用工具的相关帮助,请运行 dbutils.jobs.taskValues.help()

    get 命令 (dbutils.jobs.taskValues.get)

    在 Databricks Runtime 7.3 及更高版本中可用。

    此命令仅适用于 Python。

    在 Databricks Runtime 10.4 及更早版本上,如果 get 找不到任务,则将引发 Py4JJavaError 而不是 ValueError

    获取当前作业运行中指定任务的指定任务值的内容。

    要显示此命令的相关帮助,请运行 dbutils.jobs.taskValues.help("get")

    dbutils.jobs.taskValues.get(taskKey    = "my-task", \
                                key        = "my-key", \
                                default    = 7, \
                                debugValue = 42)
    

    在上面的示例中:

  • taskKey 是作业中任务的名称。 如果命令找不到此任务,则会引发 ValueError
  • key 是使用 set 命令 (dbutils.jobs.taskValues.set) 设置的任务值键的名称。 如果命令找不到此任务值的键,则会引发 ValueError(除非指定了 default)。
  • default 是在找不到 key 时返回的可选值。 default 不能为 None
  • debugValue 是一个可选值,如果尝试从在作业外部运行的笔记本中获取任务值,则会返回该值。 如果要手动运行笔记本并返回一些值(而不是默认引发 TypeError),则它在调试过程中很有用。 debugValue 不能为 None
  • 如果尝试从在作业外部运行的笔记本中获取任务值,则此命令将默认引发 TypeError。 但如果在命令中指定了 debugValue 参数,则会返回 debugValue 的值而不是引发 TypeError

    set 命令 (dbutils.jobs.taskValues.set)

    在 Databricks Runtime 7.3 及更高版本中可用。

    此命令仅适用于 Python。

    设置或更新任务值。 最多可为作业运行设置 250 个任务值。

    要显示此命令的相关帮助,请运行 dbutils.jobs.taskValues.help("set")

    示例包括:

    dbutils.jobs.taskValues.set(key   = "my-key", \
                                value = 5)
    dbutils.jobs.taskValues.set(key   = "my-other-key", \
                                value = "my other value")
    

    在上面的示例中:

  • key 是此任务值键的名称。 此名称对于作业必须是唯一的。
  • value 是此任务值键的值。 此命令必须能够在内部以 JSON 格式表示值。 值的 JSON 表示形式的大小不能超过 48 KiB。
  • 如果尝试从在作业外部运行的笔记本中设置任务值,则此命令不执行任何操作。

    库实用工具 (dbutils.library)

    库实用工具已弃用。

    命令:installinstallPyPIlistrestartPythonupdateCondaEnv

    可以通过库实用工具安装 Python 库并创建作用域为笔记本会话的环境。 这些库在驱动程序和执行程序上均可用,因此你可以在用户定义的函数中引用它们。 这样做可以实现以下操作:

  • 在笔记本自身中组织笔记本的库依赖项。
  • 具有不同库依赖项的笔记本用户共享群集而不受干扰。
  • 分离笔记本会破坏此环境。 但是,你可以重新创建它,只需在笔记本中重新运行库 install API 命令即可。 请参阅 restartPython API,了解如何才能重置笔记本状态而不失去环境。

    库实用工具在 Databricks Runtime ML 或用于基因组学的 Databricks Runtime 上不可用。 请改为参阅作用域为笔记本的 Python 库

    对于 Databricks Runtime 7.2 及更高版本,Databricks 建议使用 %pip magic 命令安装作用域为笔记本的库。 请参阅作用域为笔记本的 Python 库

    默认情况下,库实用工具处于启用状态。 因此,默认情况下会通过使用单独的 Python 可执行文件隔离每个笔记本的 Python 环境,该可执行文件在笔记本附加到群集并继承群集上的默认 Python 环境时创建。 通过 init script 安装到 Azure Databricks Python 环境中的库仍可用。 可以通过将 spark.databricks.libraryIsolation.enabled 设置为 false 来禁用此功能。

    此 API 与通过 UIREST API 进行的群集范围的现有库安装兼容。 通过此 API 安装的库的优先级高于群集范围的库。

    要列出可用命令,请运行 dbutils.library.help()

    install(path: String): boolean -> Install the library within the current notebook session
    installPyPI(pypiPackage: String, version: String = "", repo: String = "", extras: String = ""): boolean -> Install the PyPI library within the current notebook session
    list: List -> List the isolated libraries added for the current notebook session via dbutils
    restartPython: void -> Restart python process for the current notebook session
    updateCondaEnv(envYmlContent: String): boolean -> Update the current notebook's Conda environment based on the specification (content of environment
    

    install 命令 (dbutils.library.install)

    给定库的路径,在当前笔记本会话中安装该库。 通过调用此命令安装的库仅适用于当前笔记本。

    要显示此命令的相关帮助,请运行 dbutils.library.help("install")

    此示例在笔记本中安装 .egg.whl 库。

    Databricks Runtime 11.0 及更高版本中删除了 dbutils.library.install

    Databricks 建议将所有库安装命令放入笔记本的第一个单元,在该单元的末尾调用 restartPython。 在运行 restartPython 后会重置 Python 笔记本状态;笔记本会丢失所有状态,包括但不限于本地变量、导入的库和其他临时状态。 因此,建议在第一个笔记本单元中安装库并重置笔记本状态。

    接受的库源是 dbfsabfssadlwasbs

    dbutils.library.install("abfss:/path/to/your/library.egg")
    dbutils.library.restartPython() # Removes Python state, but some libraries might not work without calling this command.
    
    dbutils.library.install("abfss:/path/to/your/library.whl")
    dbutils.library.restartPython() # Removes Python state, but some libraries might not work without calling this command.
    

    可以使用 %pip 直接安装自定义 wheel 文件。 在以下示例中,我们假设你已将库 wheel 文件上传到 DBFS:

    %pip install /dbfs/path/to/your/library.whl
    

    pip 不支持 Egg 文件,而 wheel 被认为是 Python 构建和二进制打包的标准。 有关更多详细信息,请参阅 Wheel 和 Egg。 但是,如果想要以与 %pip 兼容的方式使用 egg 文件,则可以使用以下解决方法:

    # This step is only needed if no %pip commands have been run yet.
    # It will trigger setting up the isolated notebook environment
    %pip install <any-lib>  # This doesn't need to be a real library; for example "%pip install any-lib" would work
    
    import sys
    # Assuming the preceding step was completed, the following command
    # adds the egg file to the current notebook environment
    sys.path.append("/local/path/to/library.egg")
    

    installPyPI 命令 (dbutils.library.installPyPI)

    给定 Python Package Index (PyPI) 包,在当前笔记本会话中安装该包。 通过调用此命令安装的库在笔记本中是隔离的。

    要显示此命令的相关帮助,请运行 dbutils.library.help("installPyPI")

    此示例在笔记本中安装 PyPI 包。 versionrepoextras 是可选的。 使用 extras 参数可指定extras(额外要求)。

    dbutils.library.installPyPI("pypipackage", version="version", repo="repo", extras="extras")
    dbutils.library.restartPython()  # Removes Python state, but some libraries might not work without calling this command.
    

    Databricks Runtime 11.0 及更高版本中删除了 dbutils.library.installPyPI

    versionextras 键不能是 PyPI 包字符串的一部分。 例如,dbutils.library.installPyPI("azureml-sdk[databricks]==1.19.0") 无效。 请使用 versionextras 参数指定版本和额外信息,如下所示:

    dbutils.library.installPyPI("azureml-sdk", version="1.19.0", extras="databricks")
    dbutils.library.restartPython()  # Removes Python state, but some libraries might not work without calling this command.
    

    dbutils.library.installPyPI 命令替换为 %pip 命令时,Python 解释器将自动重启。 可以按以下方式运行安装命令:

    %pip install azureml-sdk[databricks]==1.19.0
    

    此示例在一个笔记本中指定库要求,并通过在另一个笔记本中使用 %run 进行安装。 为此,请首先定义库以便在笔记本中安装。 此示例使用名为 InstallDependencies 的笔记本。

    dbutils.library.installPyPI("torch")
    dbutils.library.installPyPI("scikit-learn", version="1.19.1")
    dbutils.library.installPyPI("azureml-sdk", extras="databricks")
    dbutils.library.restartPython() # Removes Python state, but some libraries might not work without calling this command.
    

    然后将它们安装在需要这些依赖项的笔记本中。

    %run /path/to/InstallDependencies # Install the dependencies in the first cell.
    
    import torch
    from sklearn.linear_model import LinearRegression
    import azureml
    

    此示例在维护环境时重置 Python 笔记本状态。 此方法仅在 Python 笔记本中可用。 例如,你可以使用此方法重载 Azure Databricks 预安装的不同版本的库:

    dbutils.library.installPyPI("numpy", version="1.15.4")
    dbutils.library.restartPython()
    
    # Make sure you start using the library in another cell.
    import numpy
    

    还可以使用此方法来安装需要在进程启动时加载的库(如 tensorflow):

    dbutils.library.installPyPI("tensorflow")
    dbutils.library.restartPython()
    
    # Use the library in another cell.
    import tensorflow
    

    list 命令 (dbutils.library.list)

    列出通过库实用工具为当前笔记本会话添加的独立库。 这不包括附加到群集的库。

    要显示此命令的相关帮助,请运行 dbutils.library.help("list")

    此示例列出笔记本中安装的库。

    dbutils.library.list()
    

    使用 %pip 的此命令的等效项是:

    %pip freeze
    

    restartPython 命令 (dbutils.library.restartPython)

    重新启动当前笔记本会话的 Python 进程。

    要显示此命令的相关帮助,请运行 dbutils.library.help("restartPython")

    此示例重新启动当前笔记本会话的 Python 进程。

    dbutils.library.restartPython() # Removes Python state, but some libraries might not work without calling this command.
    

    updateCondaEnv 命令 (dbutils.library.updateCondaEnv)

    基于 environment.yml 的内容更新当前笔记本的 Conda 环境。 只有 Conda 上的 Databricks Runtime 支持此方法。

    要显示此命令的相关帮助,请运行 dbutils.library.help("updateCondaEnv")

    此示例基于所提供规范的内容更新当前笔记本的 Conda 环境。

    dbutils.library.updateCondaEnv(
    channels:
      - anaconda
    dependencies:
      - gensim=3.4
      - nltk=3.4
    

    笔记本实用工具 (dbutils.notebook)

    命令:exitrun

    可以通过笔记本实用工具将笔记本链接在一起,并对其结果进行操作。 请参阅从一个 Databricks 笔记本运行另一个笔记本

    要列出可用命令,请运行 dbutils.notebook.help()

    exit(value: String): void -> This method lets you exit a notebook with a value
    run(path: String, timeoutSeconds: int, arguments: Map): String -> This method runs a notebook and returns its exit value.
    

    exit 命令 (dbutils.notebook.exit)

    使用值退出笔记本。

    要显示此命令的相关帮助,请运行 dbutils.notebook.help("exit")

    此示例使用值 Exiting from My Other Notebook 退出笔记本。

    Python

    dbutils.notebook.exit("Exiting from My Other Notebook")
    # Notebook exited: Exiting from My Other Notebook
    
    dbutils.notebook.exit("Exiting from My Other Notebook")
    # Notebook exited: Exiting from My Other Notebook
    

    Scala

    dbutils.notebook.exit("Exiting from My Other Notebook")
    // Notebook exited: Exiting from My Other Notebook
    

    如果运行包含的查询在后台运行结构化流式处理,则调用 dbutils.notebook.exit() 不会终止运行。 只要查询在后台执行,运行就会继续执行。 可单击查询单元格中的“取消”或运行 query.stop() 来停止在后台运行的查询。 查询停止时,可使用 dbutils.notebook.exit() 终止运行。

    run 命令 (dbutils.notebook.exit)

    运行笔记本并返回其退出值。 默认情况下,笔记本将在当前群集中运行。

    run 命令返回的字符串值的最大长度为 5 MB。 请参阅获取单个运行的输出 ()。

    要显示此命令的相关帮助,请运行 dbutils.notebook.help("run")

    此示例在调用笔记本的位置运行一个名为 My Other Notebook 的笔记本。 被调用的笔记本以代码行 dbutils.notebook.exit("Exiting from My Other Notebook") 结束。 如果被调用的笔记本在 60 秒内未完成运行,则会引发异常。

    Python

    dbutils.notebook.run("My Other Notebook", 60)
    # Out[14]: 'Exiting from My Other Notebook'
    

    Scala

    dbutils.notebook.run("My Other Notebook", 60)
    // res2: String = Exiting from My Other Notebook
    

    机密实用工具 (dbutils.secrets)

    命令:getgetByteslistlistScopes

    利用机密实用工具可以存储和访问敏感的凭据信息,而无需使其在笔记本中可见。 请参阅机密管理在笔记本中使用机密。 要列出可用命令,请运行 dbutils.secrets.help()

    get(scope: String, key: String): String -> Gets the string representation of a secret value with scope and key
    getBytes(scope: String, key: String): byte[] -> Gets the bytes representation of a secret value with scope and key
    list(scope: String): Seq -> Lists secret metadata for secrets within a scope
    listScopes: Seq -> Lists secret scopes
    

    get 命令 (dbutils.secrets.get)

    获取指定机密范围和密钥的机密值的字符串表示形式。

    具有权限的管理员、机密创建者和用户可读取 Azure Databricks 机密。 虽然 Azure Databricks 会努力编修笔记本中可能会显示的机密值,但没法阻止此类用户读取机密。 有关详细信息,请查看机密编修

    要显示此命令的相关帮助,请运行 dbutils.secrets.help("get")

    此示例获取名为 my-scope 的范围和名为 my-key 的密钥的机密值的字符串表示形式。

    Python

    dbutils.secrets.get(scope="my-scope", key="my-key")
    # Out[14]: '[REDACTED]'
    
    dbutils.secrets.get(scope="my-scope", key="my-key")
    # [1] "[REDACTED]"
    

    Scala

    dbutils.secrets.get(scope="my-scope", key="my-key")
    // res0: String = [REDACTED]
    

    getBytes 命令 (dbutils.secrets.getBytes)

    获取指定范围和密钥的机密值的字节表示形式。

    要显示此命令的相关帮助,请运行 dbutils.secrets.help("getBytes")

    此示例获取名为 my-scope 的范围和名为 my-key 的密钥的机密值(在示例中为 a1!b2@c3#)的字节表示形式。

    Python

    dbutils.secrets.getBytes(scope="my-scope", key="my-key")
    # Out[1]: b'a1!b2@c3#'
    
    dbutils.secrets.getBytes(scope="my-scope", key="my-key")
    # [1] 61 31 21 62 32 40 63 33 23
    

    Scala

    dbutils.secrets.getBytes(scope="my-scope", key="my-key")
    // res1: Array[Byte] = Array(97, 49, 33, 98, 50, 64, 99, 51, 35)
    

    list 命令 (dbutils.secrets.get)

    列出指定范围内的机密的元数据。

    要显示此命令的相关帮助,请运行 dbutils.secrets.help("list")

    此示例列出了名为 my-scope 的范围内机密的元数据。

    Python

    dbutils.secrets.list("my-scope")
    # Out[10]: [SecretMetadata(key='my-key')]
    
    dbutils.secrets.list("my-scope")
    # [[1]]
    # [[1]]$key
    # [1] "my-key"
    

    Scala

    dbutils.secrets.list("my-scope")
    // res2: Seq[com.databricks.dbutils_v1.SecretMetadata] = ArrayBuffer(SecretMetadata(my-key))
    

    listScopes 命令 (dbutils.secrets.listScopes)

    列出可用范围。

    要显示此命令的相关帮助,请运行 dbutils.secrets.help("listScopes")

    此示例列出可用的范围。

    Python

    dbutils.secrets.listScopes()
    # Out[14]: [SecretScope(name='my-scope')]
    
    dbutils.secrets.listScopes()
    # [[1]]
    # [[1]]$name
    # [1] "my-scope"
    

    Scala

    dbutils.secrets.listScopes()
    // res3: Seq[com.databricks.dbutils_v1.SecretScope] = ArrayBuffer(SecretScope(my-scope))
    

    小组件使用工具 (dbutils.widgets)

    命令:comboboxdropdowngetgetArgumentmultiselectremoveremoveAlltext

    通过小组件实用工具可以将笔记本参数化。 请参阅 Databricks 小组件

    要列出可用命令,请运行 dbutils.widgets.help()

    combobox(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a combobox input widget with a given name, default value and choices
    dropdown(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a dropdown input widget a with given name, default value and choices
    get(name: String): String -> Retrieves current value of an input widget
    getArgument(name: String, optional: String): String -> (DEPRECATED) Equivalent to get
    multiselect(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a multiselect input widget with a given name, default value and choices
    remove(name: String): void -> Removes an input widget from the notebook
    removeAll: void -> Removes all widgets in the notebook
    text(name: String, defaultValue: String, label: String): void -> Creates a text input widget with a given name and default value
    

    combobox 命令 (dbutils.widgets.combobox)

    使用指定的编程名称、默认值、选项和可选标签创建并显示一个 combobox 小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("combobox")

    此示例创建并显示编程名称为 fruits_combobox 的 combobox 小组件。 它提供了 applebananacoconutdragon fruit 选项并设置为初始值 banana。 此 combobox 小组件包含一个随附的标签 Fruits。 此示例以打印 combobox 小组件的初始值 banana 结束。

    Python

    dbutils.widgets.combobox(
      name='fruits_combobox',
      defaultValue='banana',
      choices=['apple', 'banana', 'coconut', 'dragon fruit'],
      label='Fruits'
    print(dbutils.widgets.get("fruits_combobox"))
    # banana
    
    dbutils.widgets.combobox(
      name='fruits_combobox',
      defaultValue='banana',
      choices=list('apple', 'banana', 'coconut', 'dragon fruit'),
      label='Fruits'
    print(dbutils.widgets.get("fruits_combobox"))
    # [1] "banana"
    

    Scala

    dbutils.widgets.combobox(
      "fruits_combobox",
      "banana",
      Array("apple", "banana", "coconut", "dragon fruit"),
      "Fruits"
    print(dbutils.widgets.get("fruits_combobox"))
    // banana
    

    dropdown 命令 (dbutils.widgets.dropdown)

    使用指定的编程名称、默认值、选项和可选标签创建并显示一个 dropdown 小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("dropdown")

    此示例创建并显示编程名称为 toys_dropdown 的 dropdown 小组件。 它提供了 alphabet blocksbasketballcapedoll 选项并设置为初始值 basketball。 此 dropdown 小组件包含一个随附的标签 Toys。 此示例以打印 dropdown 小组件的初始值 basketball 结束。

    Python

    dbutils.widgets.dropdown(
      name='toys_dropdown',
      defaultValue='basketball',
      choices=['alphabet blocks', 'basketball', 'cape', 'doll'],
      label='Toys'
    print(dbutils.widgets.get("toys_dropdown"))
    # basketball
    
    dbutils.widgets.dropdown(
      name='toys_dropdown',
      defaultValue='basketball',
      choices=list('alphabet blocks', 'basketball', 'cape', 'doll'),
      label='Toys'
    print(dbutils.widgets.get("toys_dropdown"))
    # [1] "basketball"
    

    Scala

    dbutils.widgets.dropdown(
      "toys_dropdown",
      "basketball",
      Array("alphabet blocks", "basketball", "cape", "doll"),
      "Toys"
    print(dbutils.widgets.get("toys_dropdown"))
    // basketball
    

    get 命令 (dbutils.widgets.get)

    通过指定编程名称获取小组件的当前值。 此编程名称可以是:

  • 笔记本中自定义小组件的名称,例如 fruits_comboboxtoys_dropdown
  • 作为笔记本任务的一部分传递到笔记本的自定义参数的名称,例如 nameage。 有关详细信息,请参阅创建作业 UI 中的笔记本任务的参数覆盖率或作业 API 中触发新作业运行 () 操作中的 字段。
  • 要显示此命令的相关帮助,请运行 dbutils.widgets.help("get")

    此示例获取具有编程名称 fruits_combobox 的小组件的值。

    Python

    dbutils.widgets.get('fruits_combobox')
    # banana
    
    dbutils.widgets.get('fruits_combobox')
    # [1] "banana"
    

    Scala

    dbutils.widgets.get("fruits_combobox")
    // res6: String = banana
    

    此示例获取具有编程名称 age 的笔记本任务参数的值。 当相关笔记本任务运行时,此参数设置为 35

    Python

    dbutils.widgets.get('age')
    
    dbutils.widgets.get('age')
    # [1] "35"
    

    Scala

    dbutils.widgets.get("age")
    // res6: String = 35
    

    getArgument 命令 (dbutils.widgets.getArgument)

    通过指定编程名称获取小组件的当前值。 如果小组件不存在,则可以返回可选消息。

    此命令已弃用。 请改用 dbutils.widgets.get

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("getArgument")

    此示例获取具有编程名称 fruits_combobox 的小组件的值。 如果此小组件不存在,则返回消息 Error: Cannot find fruits combobox

    Python

    dbutils.widgets.getArgument('fruits_combobox', 'Error: Cannot find fruits combobox')
    # Deprecation warning: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
    # Out[3]: 'banana'
    
    dbutils.widgets.getArgument('fruits_combobox', 'Error: Cannot find fruits combobox')
    # Deprecation warning: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
    # [1] "banana"
    

    Scala

    dbutils.widgets.getArgument("fruits_combobox", "Error: Cannot find fruits combobox")
    // command-1234567890123456:1: warning: method getArgument in trait WidgetsUtils is deprecated: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
    // dbutils.widgets.getArgument("fruits_combobox", "Error: Cannot find fruits combobox")
    //                 ^
    // res7: String = banana
    

    multiselect 命令 (dbutils.widgets.multiselect)

    创建并显示具有指定编程名称、默认值、选项和可选标签的 multiselect 小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("multiselect")

    此示例创建并显示编程名称为 days_multiselect 的 multiselect 小组件。 它通过 Sunday 提供了 Monday 选项并设置为初始值 Tuesday。 此 multiselect 小组件具有随附的标签 Days of the Week。 此示例以打印 multiselect 小组件的初始值 Tuesday 结束。

    Python

    dbutils.widgets.multiselect(
      name='days_multiselect',
      defaultValue='Tuesday',
      choices=['Monday', 'Tuesday', 'Wednesday', 'Thursday',
        'Friday', 'Saturday', 'Sunday'],
      label='Days of the Week'
    print(dbutils.widgets.get("days_multiselect"))
    # Tuesday
    
    dbutils.widgets.multiselect(
      name='days_multiselect',
      defaultValue='Tuesday',
      choices=list('Monday', 'Tuesday', 'Wednesday', 'Thursday',
        'Friday', 'Saturday', 'Sunday'),
      label='Days of the Week'
    print(dbutils.widgets.get("days_multiselect"))
    # [1] "Tuesday"
    

    Scala

    dbutils.widgets.multiselect(
      "days_multiselect",
      "Tuesday",
      Array("Monday", "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday", "Sunday"),
      "Days of the Week"
    print(dbutils.widgets.get("days_multiselect"))
    // Tuesday
    

    remove 命令 (dbutils.widgets.remove)

    删除具有指定编程名称的小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("remove")

    如果添加了命令来删除小组件,则之后不能在同一单元格中再添加命令来创建小组件。 必须在另一个单元格中创建小组件。

    此示例将删除编程名称为 fruits_combobox 的小组件。

    Python

    dbutils.widgets.remove('fruits_combobox')
    
    dbutils.widgets.remove('fruits_combobox')
    

    Scala

    dbutils.widgets.remove("fruits_combobox")
    

    removeAll 命令 (dbutils.widgets.removeAll)

    从笔记本中删除所有小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("removeAll")

    如果添加了命令来删除小组件,则之后不能在同一单元格中再添加命令来创建任何小组件。 必须在另一个单元格中创建小组件。

    此示例从笔记本中删除所有小组件。

    Python

    dbutils.widgets.removeAll()
    
    dbutils.widgets.removeAll()
    

    Scala

    dbutils.widgets.removeAll()
    

    text 命令 (dbutils.widgets.text)

    创建并显示具有指定编程名称、默认值和可选标签的 text 小组件。

    要显示此命令的相关帮助,请运行 dbutils.widgets.help("text")

    此示例创建并显示编程名称为 your_name_text 的 text 小组件。 此值设置为初始值 Enter your name。 此 text 小组件包含一个随附的标签 Your name。 此示例以打印 text 小组件的初始值 Enter your name 结束。

    Python

    dbutils.widgets.text(
      name='your_name_text',
      defaultValue='Enter your name',
      label='Your name'
    print(dbutils.widgets.get("your_name_text"))
    # Enter your name
    
    dbutils.widgets.text(
      name='your_name_text',
      defaultValue='Enter your name',
      label='Your name'
    print(dbutils.widgets.get("your_name_text"))
    # [1] "Enter your name"
    

    Scala

    dbutils.widgets.text(
      "your_name_text",
      "Enter your name",
      "Your name"
    print(dbutils.widgets.get("your_name_text"))
    // Enter your name
    

    Databricks 实用工具 API 库

    为了加快应用程序开发,可以在将应用程序部署为生产作业之前对其进行编译、构建和测试。 为了让你能够针对 Databricks 实用工具进行编译,Databricks 提供了 dbutils-api 库。 可以从 Maven Repository 网站上的 dbutils-api 网页下载 dbutils-api 库,也可以通过将依赖项添加到生成文件来加入库:

    libraryDependencies += "com.databricks" % "dbutils-api_TARGET" % "VERSION"
    
  • Maven

    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>dbutils-api_TARGET</artifactId>
        <version>VERSION</version>
    </dependency>
    
  • Gradle

    compile 'com.databricks:dbutils-api_TARGET:VERSION'
    

    TARGET 替换为所需的目标(例如 2.12),并将 VERSION 替换为所需版本(例如 0.0.5)。 有关可用目标和版本的列表,请参阅 Maven Repository 网站上的 DBUtils API 网页。

    针对此库生成应用程序后,即可部署该应用程序。

    dbutils-api 库允许你在本地编译一个使用 dbutils 的应用程序,但不允许你运行它。 若要运行该应用程序,必须将其部署到 Azure Databricks 中。

    在执行程序内调用 dbutils 可能会产生意外的结果或可能导致错误。

    如果需要使用 dbutils 在执行程序上运行文件系统操作,可以使用以下几种可快速且更具扩展性的替代方法:

  • 对于文件复制或移动操作,可以选择将文件系统操作并行化中所述的更快速运行文件系统操作的操作。
  • 对于文件系统列出和删除操作,可以参考如何在 Databricks 中更快地列出和删除文件中利用 Spark 的并行列出和删除方法。
  • 有关执行器的信息,请参阅 Apache Spark 网站上的集群模式概述

  •