如何使用 Rust 使用默认程序启动任何文件(如 Python 的 `os.startfile()`)

How launch any file using default program using Rust (like Python's `os.startfile()`)

python中是否有等同于os.startfile()的rust方法。例如,我需要使用 Rust 启动一个“mp3 文件”。在 python 中是 os.startfile('audio.mp3')。这将打开默认媒体播放器并开始播放该文件。我需要用 Rust 语言做同样的事情。

Python 的 os.startfile() 函数仅在 Windows 上可用,它只是 ShellExecuteW() in the Windows API. You can call this function via the winapi crate.

的包装器

更简单、更便携的解决方案是使用 open crate

目前发现有两种方法可以在多个 OS 平台(Mac、Windows 和 Linux)上工作。我也亲自测试过。
方法一: 使用 opener 个箱子 (link) 在 Windows 上使用 ShellExecuteW Windows API 函数。在 Mac 上使用系统 open 命令。在其他平台上,使用 xdg-open 脚本。系统xdg-open未使用;相反,该库中嵌入了一个版本。

rs file(src/main.rs):

中使用以下代码
// open a file
let result = opener::open(std::path::Path::new("Cargo.toml"));
println!("{:?}", result); // for viewing errors if any captured in the variable result

在依赖项部分的“Cargo.toml”文件中使用以下代码:

opener = "0.4.1"

方法二: 使用 open 箱子 (link) 使用此库打开路径或使用系统上配置的程序 URL。它等同于 运行 以下之一:open <path-or-url>(OSX), start <path-or-url> (Windows), xdg-open <path-or-url> || gio open <path-or-url> || gnome-open <path-or-url> || kde-open <path-or-url> || wslview <path-or-url> (Linux).

rs file(src/main.rs)中使用以下代码:

// to open the file using the default application
open::that("Cargo.toml");
// if you want to open the file with a specific program you should use the following
open::with("Cargo.toml", "notepad");

在依赖项部分的“Cargo.toml”文件中使用以下代码:

open = "1.7.0"

希望对所有人有用。