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

2024-05-20 19:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件方法语言osrustmp3audio媒体播放器
1条回答
网友
1楼 · 发布于 2024-05-20 19:53:44

Python的os.startfile()函数仅在Windows上可用,它只是Windows API中^{}的包装器。你可以call this function via the ^{} crate

一个更简单、更可移植的解决方案是使用^{} crate

网友
2楼 · 发布于 2024-05-20 19:53:44

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

rs filesrc/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"

方法2: 使用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 filesrc/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"

希望它对所有人都有效

相关问题 更多 >