Databricks 公用程式 (dbutils
) 參考
本文是 Databricks Utilities (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.
credentials: DatabricksCredentialUtils -> Utilities for interacting with credentials within notebooks
data: DataUtils -> Utilities for understanding and interacting with datasets (EXPERIMENTAL)
fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the console
jobs: JobsUtils -> Utilities for leveraging jobs features
library: LibraryUtils -> Utilities for session isolated libraries
meta: MetaUtils -> Methods to hook into the compiler (EXPERIMENTAL)
notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)
preview: Preview -> Utilities under preview category
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()
R
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")
R
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。
此命令會分析 DataFrame 的完整內容。 針對非常大型的 DataFrame 執行此命令可能非常昂貴。
若要顯示此指令的說明,請執行 dbutils.data.help("summarize")
。
在 Databricks Runtime 10.4 LTS 和更新版本中,您可以使用其他 precise
參數來調整計算統計數據的有效位數。
注意
這項功能處於公開預覽狀態。
- 當
precise
設定為 false 時(預設值),某些傳回的統計數據會包含近似值,以減少運行時間。- 類別數據行的相異值數目對於高基數數據行可能有 ~5% 的相對錯誤。
- 當相異值的數目大於 10000 時,頻繁的值計數可能會有最多 0.01% 的錯誤。
- 直方圖和百分位數估計值可能會有相對於數據列總數的0.01%的錯誤。
- 當 設定為 true 時
precise
,統計數據會以較高的精確度計算。 除了數值數據行的直方圖和百分位數之外,所有統計數據現在都是確切的。- 直方圖和百分位數估計值可能相對於數據列總數的誤差高達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)
R
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
。 其中一個例外:視覺效果會針對 (giga) 使用 「B
而不是」 而不是 1.0e9
」。G
檔案系統公用程式 (dbutils.fs)
警告
所有 dbutils.fs
方法的 Python 實作都會使用 snake_case
,而不是 camelCase
用於關鍵詞格式設定。
例如:在 dbutils.fs.help()
Python 中顯示 的選項extraConfigs
dbutils.fs.mount()
時,您會使用 關鍵詞 extra_configs
。
命令: cp, head, ls, mkdirs, mount, mounts, mv, put, refreshMounts, rm, unmount, updateMount
文件系統公用程式可讓您存取 什麼是 DBFS?,讓您更輕鬆地使用 Azure Databricks 作為文件系統。
在筆記本中,您也可以使用 %fs
magic命令來存取 DBFS。 例如 %fs ls /Volumes/main/default/my-volume/
,與 dbutils.fs.ls("/Volumes/main/default/my-volume/")
相同。 請參閱 magic命令。
若要列出可用的命令,請執行 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")
。
本範例會將名為 data.csv
的/Volumes/main/default/my-volume/
new-data.csv
檔案複製到相同的磁碟區中。
Python
dbutils.fs.cp("/Volumes/main/default/my-volume/data.csv", "/Volumes/main/default/my-volume/new-data.csv")
# Out[4]: True
R
dbutils.fs.cp("/Volumes/main/default/my-volume/data.csv", "/Volumes/main/default/my-volume/new-data.csv")
# [1] TRUE
Scala
dbutils.fs.cp("/Volumes/main/default/my-volume/data.csv", "/Volumes/main/default/my-volume/new-data.csv")
// res3: Boolean = true
head 命令 (dbutils.fs.head)
傳回指定檔案的指定最大位元元組數。 位元組會以UTF-8編碼字串的形式傳回。
若要顯示此指令的說明,請執行 dbutils.fs.help("head")
。
這個範例會顯示位於 /Volumes/main/default/my-volume/
中的檔案前 25 個字節data.csv
。
Python
dbutils.fs.head("/Volumes/main/default/my-volume/data.csv", 25)
# [Truncated to first 25 bytes]
# Out[12]: 'Year,First Name,County,Se'
R
dbutils.fs.head("/Volumes/main/default/my-volume/data.csv", 25)
# [1] "Year,First Name,County,Se"
Scala
dbutils.fs.head("/Volumes/main/default/my-volume/data.csv", 25)
// [Truncated to first 25 bytes]
// res4: String =
// "Year,First Name,County,Se"
ls 命令 (dbutils.fs.ls)
列出目錄的內容。
若要顯示此指令的說明,請執行 dbutils.fs.help("ls")
。
此範例會顯示 的內容 /Volumes/main/default/my-volume/
相關信息。 欄位 modificationTime
可在 Databricks Runtime 10.4 LTS 和更新版本中使用。 在 R 中, modificationTime
會以字串的形式傳回。
Python
dbutils.fs.ls("/Volumes/main/default/my-volume/")
# Out[13]: [FileInfo(path='dbfs:/Volumes/main/default/my-volume/data.csv', name='data.csv', size=2258987, modificationTime=1711357839000)]
R
dbutils.fs.ls("/Volumes/main/default/my-volume/")
# For prettier results from dbutils.fs.ls(<dir>), please use `%fs ls <dir>`
# [[1]]
# [[1]]$path
# [1] "/Volumes/main/default/my-volume/data.csv"
# [[1]]$name
# [1] "data.csv"
# [[1]]$size
# [1] 2258987
# [[1]]$isDir
# [1] FALSE
# [[1]]$isFile
# [1] TRUE
# [[1]]$modificationTime
# [1] "1711357839000"
Scala
dbutils.fs.ls("/tmp")
// res6: Seq[com.databricks.backend.daemon.dbutils.FileInfo] = WrappedArray(FileInfo(/Volumes/main/default/my-volume/data.csv, 2258987, 1711357839000))
mkdirs 命令 (dbutils.fs.mkdirs)
如果指定的目錄不存在,則建立該目錄。 也會建立任何必要的父目錄。
若要顯示此指令的說明,請執行 dbutils.fs.help("mkdirs")
。
此範例會在內/Volumes/main/default/my-volume/
建立 目錄my-data
。
Python
dbutils.fs.mkdirs("/Volumes/main/default/my-volume/my-data")
# Out[15]: True
R
dbutils.fs.mkdirs("/Volumes/main/default/my-volume/my-data")
# [1] TRUE
Scala
dbutils.fs.mkdirs("/Volumes/main/default/my-volume/my-data")
// 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")
。
警告
呼叫 dbutils.fs.refreshMounts()
所有其他執行中的叢集,以傳播新的掛接。 請參閱 refreshMounts 命令 (dbutils.fs.refreshMounts) 。
Python
dbutils.fs.mounts()
Scala
dbutils.fs.mounts()
如需其他程式代碼範例,請參閱 連線到 Azure Data Lake Storage Gen2 和 Blob 記憶體。
mv 命令 (dbutils.fs.mv)
移動檔案或目錄,可能跨文件系統移動。 移動是一個複本,後面接著刪除,即使是在文件系統內移動也一般。
若要顯示此指令的說明,請執行 dbutils.fs.help("mv")
。
本範例會將檔案 rows.csv
從 /Volumes/main/default/my-volume/
移至 /Volumes/main/default/my-volume/my-data/
。
Python
dbutils.fs.mv("/Volumes/main/default/my-volume/rows.csv", "/Volumes/main/default/my-volume/my-data/")
# Out[2]: True
R
dbutils.fs.mv("/Volumes/main/default/my-volume/rows.csv", "/Volumes/main/default/my-volume/my-data/")
# [1] TRUE
Scala
dbutils.fs.mv("/Volumes/main/default/my-volume/rows.csv", "/Volumes/main/default/my-volume/my-data/")
// res1: Boolean = true
put 命令 (dbutils.fs.put)
將指定的字串寫入檔案。 字串為UTF-8編碼。
若要顯示此指令的說明,請執行 dbutils.fs.help("put")
。
這個範例會將字串 Hello, Databricks!
寫入至 中名為 hello.txt
的 /Volumes/main/default/my-volume/
檔案。 如果檔案存在,則會覆寫它。
Python
dbutils.fs.put("/Volumes/main/default/my-volume/hello.txt", "Hello, Databricks!", True)
# Wrote 2258987 bytes.
# Out[6]: True
R
dbutils.fs.put("/Volumes/main/default/my-volume/hello.txt", "Hello, Databricks!", TRUE)
# [1] TRUE
Scala
dbutils.fs.put("/Volumes/main/default/my-volume/hello.txt", "Hello, Databricks!", true)
// Wrote 2258987 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.rm)
拿掉檔案或目錄,並選擇性地移除其所有內容。 如果指定檔案,則會忽略遞歸參數。 如果指定了目錄,如果停用遞歸,而且目錄不是空的,就會發生錯誤。
若要顯示此指令的說明,請執行 dbutils.fs.help("rm")
。
此範例會移除目錄 /Volumes/main/default/my-volume/my-data/
,包括目錄的內容。
Python
dbutils.fs.rm("/Volumes/main/default/my-volume/my-data/", True)
# Out[8]: True
R
dbutils.fs.rm("/Volumes/main/default/my-volume/my-data/", TRUE)
# [1] TRUE
Scala
dbutils.fs.rm("/Volumes/main/default/my-volume/my-data/", true)
// res6: Boolean = true
unmount 命令 (dbutils.fs.unmount)
刪除 DBFS 載入點。
警告
若要避免錯誤,請勿在其他作業讀取或寫入時修改裝入點。 修改掛接之後,請一律在所有其他執行中的叢集上執行 dbutils.fs.refreshMounts()
,以傳播任何掛接更新。 請參閱 refreshMounts 命令 (dbutils.fs.refreshMounts) 。
若要顯示此指令的說明,請執行 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")
。
警告
若要避免錯誤,請勿在其他作業讀取或寫入時修改裝入點。 修改掛接之後,請一律在所有其他執行中的叢集上執行 dbutils.fs.refreshMounts()
,以傳播任何掛接更新。 請參閱 refreshMounts 命令 (dbutils.fs.refreshMounts) 。
此命令可在 Databricks Runtime 10.4 LTS 和更新版本中使用。
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
注意
此公用程式僅適用於 Python。
作業公用程式可讓您利用作業功能。 若要顯示此公用程式的說明,請執行 dbutils.jobs.help()
。
Provides utilities for leveraging jobs features.
taskValues: TaskValuesUtils -> Provides utilities for leveraging job task values
taskValues 子公用程式 (dbutils.jobs.taskValues)
注意
此子公用程式僅適用於 Python。
提供運用作業工作值的命令。
使用此子公用程式,在作業執行期間設定和取得任意值。 這些值稱為 工作值。 您可以在相同作業執行中存取下游工作中的工作值。 例如,您可以在作業執行內的不同工作之間傳達標識碼或計量,例如機器學習模型評估的相關信息。 每個工作都可以設定多個工作值、取得這些值或兩者。 每個工作值在相同的工作中都有唯一索引鍵。 這個唯一索引鍵稱為工作值的索引鍵。 工作值是使用工作名稱和工作值索引鍵來存取。
若要顯示此子使用量的說明,請執行 dbutils.jobs.taskValues.help()
。
get 命令 (dbutils.jobs.taskValues.get)
注意
此命令僅適用於 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)
注意
此命令僅適用於 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
是工作值的索引鍵。 此索引鍵對工作而言必須是唯一的。 也就是說,如果兩個不同的工作都會使用索引鍵來設定工作值,這些是具有相同索引鍵K
K
的兩個不同的工作值。value
是此工作值索引鍵的值。 此命令必須能夠以 JSON 格式在內部表示值。 值的 JSON 表示大小不能超過 48 KiB。
如果您嘗試從在作業外部執行的筆記本中設定工作值,此命令不會執行任何動作。
連結庫公用程式 (dbutils.library)
子模組中的 dbutils.library
大部分方法已被取代。 請參閱 連結庫公用程式 (dbutils.library) (legacy)。
您可能需要以程式設計方式重新啟動 Azure Databricks 上的 Python 程式,以確保本機安裝或升級的連結庫在 Python 核心中正常運作,以取得目前的 SparkSession。 若要這樣做,請執行 dbutils.library.restartPython
命令。 請參閱 在 Azure Databricks 上重新啟動 Python 程式。
筆記本公用程式 (dbutils.notebook)
Notebook 公用程式可讓您將筆記本鏈結在一起,並對其結果採取行動。 請參閱 從另一個筆記本執行 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
R
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.run)
執行筆記本並傳回其結束值。 筆記本預設會在目前的叢集中執行。
注意
從 run
命令傳回的字串值長度上限為 5 MB。 請參閱 取得單一執行 (GET /jobs/runs/get-output
) 的輸出。
若要顯示此指令的說明,請執行 dbutils.notebook.help("run")
。
此範例會在與呼叫筆記本相同的位置執行名為 My Other Notebook
的筆記本。 呼叫的 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)
命令:get、getBytes、list、listScopes
秘密公用程式可讓您儲存和存取敏感性認證資訊,而不會在筆記本中顯示它們。 請參閱秘密管理和使用筆記本中的秘密。 若要列出可用的命令,請執行 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]'
R
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#'
R
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.list)
列出指定範圍內秘密的元數據。
若要顯示此指令的說明,請執行 dbutils.secrets.help("list")
。
此範例會列出名為 my-scope
的範圍內秘密的元數據。
Python
dbutils.secrets.list("my-scope")
# Out[10]: [SecretMetadata(key='my-key')]
R
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')]
R
dbutils.secrets.listScopes()
# [[1]]
# [[1]]$name
# [1] "my-scope"
Scala
dbutils.secrets.listScopes()
// res3: Seq[com.databricks.dbutils_v1.SecretScope] = ArrayBuffer(SecretScope(my-scope))
Widgets 公用程式 (dbutils.widgets)
命令:下拉式方塊、下拉式清單、get、getArgument、multiselect、remove、removeAll、text
Widgets 公用程式可讓您將筆記本參數化。 請參閱 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
getAll: map -> Retrieves a map of all widget names and their values
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)
使用指定的程式設計名稱、預設值、選項和選擇性標籤,建立並顯示下拉式方塊小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("combobox")
。
此範例會建立並顯示具有程式設計名稱 fruits_combobox
的下拉式方塊小工具。 它提供選項、、 和 ,且 dragon fruit
會設定為 的初始值banana
。 coconut
banana
apple
此下拉式方塊小工具具有隨附的標籤 Fruits
。 此範例會以列印下拉式方塊小工具 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
R
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
SQL
CREATE WIDGET COMBOBOX fruits_combobox DEFAULT "banana" CHOICES SELECT * FROM (VALUES ("apple"), ("banana"), ("coconut"), ("dragon fruit"))
SELECT :fruits_combobox
-- banana
下拉式清單命令 (dbutils.widgets.dropdown)
使用指定的程式設計名稱、預設值、選項和選擇性標籤,建立並顯示下拉式清單小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("dropdown")
。
此範例會建立並顯示具有程式設計名稱 toys_dropdown
的下拉式小工具。 它提供選項、、 和 ,且 doll
會設定為 的初始值basketball
。 cape
basketball
alphabet blocks
這個下拉式清單小工具具有隨附的標籤 Toys
。 此範例的結尾是列印下拉式小工具 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
R
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
SQL
CREATE WIDGET DROPDOWN toys_dropdown DEFAULT "basketball" CHOICES SELECT * FROM (VALUES ("alphabet blocks"), ("basketball"), ("cape"), ("doll"))
SELECT :toys_dropdown
-- basketball
get 命令 (dbutils.widgets.get)
取得具有指定程式設計名稱之小工具的目前值。 這個程式設計名稱可以是:
- 筆記本中的自訂小工具名稱,例如
fruits_combobox
或toys_dropdown
。 - 做為筆記本工作的一部分傳遞至筆記本的自訂參數名稱,例如
name
或age
。 如需詳細資訊,請參閱建立作業 UI 中的筆記本工作參數涵蓋範圍,或在notebook_params
作業 API 中觸發新作業執行 (POST /jobs/run-now
) 作業中的 字段。
若要顯示此指令的說明,請執行 dbutils.widgets.help("get")
。
這個範例會取得具有程式設計名稱 fruits_combobox
的小工具值。
Python
dbutils.widgets.get('fruits_combobox')
# banana
R
dbutils.widgets.get('fruits_combobox')
# [1] "banana"
Scala
dbutils.widgets.get("fruits_combobox")
// res6: String = banana
SQL
SELECT :fruits_combobox
-- banana
這個範例會取得具有程序設計名稱 age
的筆記本工作參數值。 當相關的筆記本工作執行時,此參數已設定為 35
。
Python
dbutils.widgets.get('age')
# 35
R
dbutils.widgets.get('age')
# [1] "35"
Scala
dbutils.widgets.get("age")
// res6: String = 35
SQL
SELECT :age
-- 35
getAll 命令 (dbutils.widgets.getAll)
取得所有目前小工具名稱和值的對應。 這對於快速將小工具值傳遞至 spark.sql()
查詢特別有用。
此命令可在 Databricks Runtime 13.3 LTS 和更新版本中使用。 它僅適用於 Python 和 Scala。
若要顯示此指令的說明,請執行 dbutils.widgets.help("getAll")
。
此範例會取得小工具值的對應,並將它當做Spark SQL查詢中的參數自變數傳遞。
Python
df = spark.sql("SELECT * FROM table where col1 = :param", dbutils.widgets.getAll())
df.show()
# Query output
Scala
val df = spark.sql("SELECT * FROM table where col1 = :param", dbutils.widgets.getAll())
df.show()
// res6: Query output
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'
R
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)
使用指定的程式設計名稱、預設值、選項和選擇性標籤,建立並顯示多重選取小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("multiselect")
。
此範例會建立並顯示具有程序設計名稱 days_multiselect
的多選小工具。 它會透過 提供選項Monday
,並將設定為的初始值Tuesday
。Sunday
這個多重選取小工具具有隨附的標籤 Days of the Week
。 此範例的結尾是列印多重選取小工具 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
R
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
SQL
CREATE WIDGET MULTISELECT days_multiselect DEFAULT "Tuesday" CHOICES SELECT * FROM (VALUES ("Monday"), ("Tuesday"), ("Wednesday"), ("Thursday"), ("Friday"), ("Saturday"), ("Sunday"))
SELECT :days_multiselect
-- Tuesday
remove 命令 (dbutils.widgets.remove)
拿掉具有指定程式設計名稱的小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("remove")
。
重要
如果您新增命令以移除小工具,則無法新增後續命令,以在相同的數據格中建立小工具。 您必須在另一個儲存格中建立小工具。
此範例會移除具有程式設計名稱 fruits_combobox
的小工具。
Python
dbutils.widgets.remove('fruits_combobox')
R
dbutils.widgets.remove('fruits_combobox')
Scala
dbutils.widgets.remove("fruits_combobox")
SQL
REMOVE WIDGET fruits_combobox
removeAll 命令 (dbutils.widgets.removeAll)
從筆記本中移除所有小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("removeAll")
。
重要
如果您新增命令以移除所有小工具,則無法新增後續命令,以在相同的數據格中建立任何小工具。 您必須在另一個儲存格中建立小工具。
此範例會從筆記本中移除所有小工具。
Python
dbutils.widgets.removeAll()
R
dbutils.widgets.removeAll()
Scala
dbutils.widgets.removeAll()
text 命令 (dbutils.widgets.text)
使用指定的程式設計名稱、預設值和選擇性標籤,建立並顯示文字小工具。
若要顯示此指令的說明,請執行 dbutils.widgets.help("text")
。
此範例會建立並顯示具有程序設計名稱 your_name_text
的文字小工具。 它會設定為 的初始值 Enter your name
。 這個文字小工具具有隨附的標籤 Your name
。 此範例的結尾是列印文字小工具 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
R
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
SQL
CREATE WIDGET TEXT your_name_text DEFAULT "Enter your name"
SELECT :your_name_text
-- Enter your name
Databricks 公用程式 API 連結庫
重要
Databricks 公用程式 API (dbutils-api
) 連結庫已被取代。 雖然此連結庫仍可供使用,但 Databricks 不會規劃連結 dbutils-api
庫的新功能。
Databricks 建議您改用下列其中一個連結庫:
若要加速應用程式開發,在將應用程式部署為生產作業之前,先編譯、建置及測試應用程式會很有説明。 為了讓您能夠針對 Databricks 公用程式進行編譯,Databricks 會提供連結 dbutils-api
庫。 您可以從 Maven 存放庫網站上的 DBUtils API 網頁下載連結dbutils-api
庫,或藉由將相依性新增至組建檔案來包含連結庫:
SBT
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 存放庫網站上的 DBUtils API 網頁。
一旦您針對此連結庫建置應用程式,您就可以部署應用程式。
重要
連結 dbutils-api
庫可讓您在本機編譯使用 dbutils
的應用程式,但無法執行它。 若要執行應用程式,您必須在 Azure Databricks 中部署它。
限制
在執行程式內部呼叫 dbutils
可能會產生非預期的結果或可能導致錯誤。
如果您需要使用 dbutils
在執行程式上執行檔案系統作業,有數個更快速且更具擴充性的替代方案可供使用:
- 針對檔案複製或移動作業,您可以檢查平行處理檔案系統作業中所述執行檔案系統作業的更快速選項。
- 針對檔案系統清單和刪除作業,您可以在 Databricks 中參考使用 Spark 的平行清單和刪除方法。
如需執行程式的相關信息,請參閱 Apache Spark 網站上的叢集模式概觀 。