3

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

4

2 回答 2

4

Python 的os.startfile()函数仅在 Windows 上可用,它只是ShellExecuteW()Windows API 中的一个包装器。您可以通过crate调用此函数winapi

一个更简单、更便携的解决方案是使用opencrate

于 2021-05-19T08:25:39.760 回答
0

到目前为止,有两种方法可以在多个操作系统平台(Mac、Windows 和 Linux)上工作。我也亲自测试过。
方法 1: 使用openercrate (链接) 在 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"

方法二: 使用opencrate ( 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"

希望它对所有人都有效。

于 2021-05-19T09:41:02.303 回答