Skip to main content

Command

Struct Command 

Source
pub struct Command { /* private fields */ }
Expand description

The type to spawn commands.

Implementations§

Source§

impl Command

Source

pub fn arg<S: AsRef<OsStr>>(self, arg: S) -> Self

Appends an argument to the command.

Source

pub fn args<I, S>(self, args: I) -> Self
where I: IntoIterator<Item = S>, S: AsRef<OsStr>,

Appends arguments to the command.

Source

pub fn env_clear(self) -> Self

Clears the entire environment map for the child process.

Source

pub fn env<K, V>(self, key: K, value: V) -> Self
where K: AsRef<OsStr>, V: AsRef<OsStr>,

Inserts or updates an explicit environment variable mapping.

Source

pub fn envs<I, K, V>(self, envs: I) -> Self
where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>,

Adds or updates multiple environment variable mappings.

Source

pub fn current_dir<P: AsRef<Path>>(self, current_dir: P) -> Self

Sets the working directory for the child process.

Source

pub fn set_raw_out(self, raw_out: bool) -> Self

Configures the reader to output bytes from the child process exactly as received

Source

pub fn set_process_group(self, process_group: bool) -> Self

Configures the command to spawn in a new process group (POSIX) or job object (Windows).

When enabled, killing the child process will also kill all processes in the group, which is useful for programs that spawn child processes (e.g. PyInstaller wrappers).

Source

pub fn spawn(self) -> Result<(Receiver<CommandEvent>, CommandChild), Error>

Spawns the command.

§Examples
use tauri_plugin_shell::{process::CommandEvent, ShellExt};
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle().clone();
    tauri::async_runtime::spawn(async move {
      let (mut rx, mut child) = handle
        .shell()
        .command("cargo")
        .args(["tauri", "dev"])
        .spawn()
        .expect("Failed to spawn cargo");

      let mut i = 0;
      while let Some(event) = rx.recv().await {
        if let CommandEvent::Stdout(line) = event {
          println!("got: {}", String::from_utf8(line).unwrap());
          i += 1;
          if i == 4 {
            child.write("message from Rust\n".as_bytes()).unwrap();
            i = 0;
          }
        }
      }
    });
    Ok(())
  });

Depending on the command you spawn, it might output in a specific encoding, to parse the output lines in this case:

use tauri_plugin_shell::{process::{CommandEvent, Encoding}, ShellExt};
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle().clone();
    tauri::async_runtime::spawn(async move {
      let (mut rx, mut child) = handle
        .shell()
        .command("some-program")
        .arg("some-arg")
        .spawn()
        .expect("Failed to spawn some-program");

      let encoding = Encoding::for_label(b"windows-1252").unwrap();
      while let Some(event) = rx.recv().await {
        if let CommandEvent::Stdout(line) = event {
          let (decoded, _, _) = encoding.decode(&line);
          println!("got: {decoded}");
        }
      }
    });
    Ok(())
  });
Source

pub async fn status(self) -> Result<ExitStatus, Error>

Executes a command as a child process, waiting for it to finish and collecting its exit status. Stdin, stdout and stderr are ignored.

§Examples
use tauri_plugin_shell::ShellExt;
tauri::Builder::default()
  .setup(|app| {
    let status = tauri::async_runtime::block_on(async move { app.shell().command("which").args(["ls"]).status().await.unwrap() });
    println!("`which` finished with status: {:?}", status.code());
    Ok(())
  });
Source

pub async fn output(self) -> Result<Output, Error>

Executes the command as a child process, waiting for it to finish and collecting all of its output. Stdin is ignored.

§Examples
use tauri_plugin_shell::ShellExt;
tauri::Builder::default()
  .setup(|app| {
    let output = tauri::async_runtime::block_on(async move { app.shell().command("echo").args(["TAURI"]).output().await.unwrap() });
    assert!(output.status.success());
    assert_eq!(String::from_utf8(output.stdout).unwrap(), "TAURI");
    Ok(())
  });

Trait Implementations§

Source§

impl Debug for Command

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Command> for Command

Source§

fn from(cmd: Command) -> StdCommand

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> MaybeSendSync for T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.