Finding executable in PATH with Rust -
in python can:
from distutils import spawn cmd = spawn.find_executable("commandname")
i tried code below, it assumes you're on unix-like system /usr/bin/which
available(also involves execution of external command want avoid):
use std::process::command; let output = command::new("which") .arg("commandname") .unwrap_or_else(|e| /* handle error here */)
what simplest way in rust?
i'd grab environment variable , iterate through it, returning first matching path:
use std::env; use std::path::{path, pathbuf}; fn find_it<p>(exe_name: p) -> option<pathbuf> p: asref<path>, { env::var_os("path").and_then(|paths| { env::split_paths(&paths).filter_map(|dir| { let full_path = dir.join(&exe_name); if full_path.is_file() { some(full_path) } else { none } }).next() }) } fn main() { println!("{:?}", find_it("cat")); println!("{:?}", find_it("dog")); }
this ugly on windows you'd have append .exe
executable name. should potentially extended return items executable, again platform-specific code.
reviewing python implementation, appears support absolute path being passed. that's if function should support or not.
a quick search on crates.io returned 1 crate may useful: quale, although says
currently works on unix-like operating systems.
it wouldn't surprise me find out there others.
here's ugly code adds .exe
end if it's missing, on windows.
#[cfg(not(target_os = "windows"))] fn enhance_exe_name(exe_name: &path) -> cow<path> { exe_name.into() } #[cfg(target_os = "windows")] fn enhance_exe_name(exe_name: &path) -> cow<path> { use std::ffi::osstr; use std::os::windows::ffi::osstrext; let raw_input: vec<_> = exe_name.as_os_str().encode_wide().collect(); let raw_extension: vec<_> = osstr::new(".exe").encode_wide().collect(); if raw_input.ends_with(&raw_extension) { exe_name.into() } else { let mut with_exe = exe_name.as_os_str().to_owned(); with_exe.push(".exe"); pathbuf::from(with_exe).into() } } // @ top of `find_it` function: // let exe_name = enhance_exe_name(exe_name.as_ref());
Comments
Post a Comment