Is there a rust method equivalent to os.startfile()
in python. For example, I need to launch an "mp3 file" using rust. In python it is os.startfile('audio.mp3')
. This will open default media player and start playing that file. I need to do the same with Rust Language.

- 27,633
- 5
- 85
- 95

- 153
- 2
- 12
2 Answers
Python's os.startfile()
function is only available on Windows, and it's just a wrapper around ShellExecuteW()
in the Windows API. You can call this function via the winapi
crate.
An easier and more portable solution is using the open
crate.

- 574,206
- 118
- 941
- 841
-
1@SantoK.Thomas The `open` crate looks like it explicitly supports Windows, MacOS, iOS, and other Unix systems through `xdg-open` and others. – user4815162342 May 19 '21 at 08:48
There are two ways that will work over multiple OS platforms (Mac, Windows, and Linux) found so far. I have personally tested it as well.
Method 1:
Use opener
crate (link)
On Windows the ShellExecuteW
Windows API function is used. On Mac the system open
command is used. On other platforms, the xdg-open
script is used. The system xdg-open
is not used; instead a version is embedded within this library.
Use the following code in the 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
Use the following code in the "Cargo.toml" file in the dependencies section:
opener = "0.4.1"
Method 2:
Use open
crate (link)
Use this library to open a path or URL using the program configured on the system. It is equivalent to running one of the following: 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).
Use the following code in the 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");
Use the following code in the "Cargo.toml" file in the dependencies section:
open = "1.7.0"
Hope it works to all.

- 153
- 2
- 12
-
What is the difference between these two crates, they seem to be solving the exact same problem, and both seem to be maintained? – bobbaluba Mar 23 '23 at 15:02