Command

Struct Command 

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

A process builder, providing fine-grained control over how a new process should be spawned.

A default configuration can be generated using Command::new(program), where program gives a path to the program to be executed. Additional builder methods allow the configuration to be changed (for example, by adding arguments) prior to spawning:

use wasi_net::Command;

let output = if cfg!(target_os = "windows") {
    Command::new("cmd")
            .args(&["/C", "echo hello"])
            .output()
            .expect("failed to execute process")
} else {
    Command::new("sh")
            .arg("-c")
            .arg("echo hello")
            .output()
            .expect("failed to execute process")
};

let hello = output.stdout;

Command can be reused to spawn multiple processes. The builder methods change the command without needing to immediately spawn the process.

use wasi_net::Command;

let mut echo_hello = Command::new("sh");
echo_hello.arg("-c")
          .arg("echo hello");
let hello_1 = echo_hello.output().expect("failed to execute process");
let hello_2 = echo_hello.output().expect("failed to execute process");

Similarly, you can call builder methods after spawning a process and then spawn a new process with the modified settings.

use wasi_net::Command;

let mut list_dir = Command::new("ls");

// Execute `ls` in the current directory of the program.
list_dir.status().expect("process failed to execute");

Implementations§

Source§

impl Command

Source

pub fn new(path: &str) -> Command

Constructs a new Command for launching the program at path program, with the following default configuration:

  • No arguments to the program
  • Inherit the current process’s environment
  • Inherit the current process’s working directory
  • Inherit stdin/stdout/stderr for spawn or status, but create pipes for output

Builder methods are provided to change these defaults and otherwise configure the process.

If program is not an absolute path, the PATH will be searched in an OS-defined way.

§Examples

Basic usage:

use wasi_net::Command;

Command::new("sh")
        .spawn()
        .expect("sh command failed to start");
Source

pub fn arg(&mut self, arg: &str) -> &mut Command

Adds an argument to pass to the program.

Only one argument can be passed per use. So instead of:

.arg("-C /path/to/repo")

usage would be:

.arg("-C")
.arg("/path/to/repo")

To pass multiple arguments see args.

Note that the argument is not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect.

§Examples

Basic usage:

use wasi_net::Command;

Command::new("ls")
        .arg("-l")
        .arg("-a")
        .spawn()
        .expect("ls command failed to start");
Source

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

Adds multiple arguments to pass to the program.

To pass a single argument see arg.

Note that the arguments are not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect.

§Examples

Basic usage:

use wasi_net::Command;

Command::new("ls")
        .args(&["-l", "-a"])
        .spawn()
        .expect("ls command failed to start");
Source

pub fn current_dir(&mut self, dir: &str) -> &mut Command

Sets the working directory for the child process.

§Platform-specific behavior

If the program path is relative (e.g., "./script.sh"), it’s ambiguous whether it should be interpreted relative to the parent’s working directory or relative to current_dir. The behavior in this case is platform specific and unstable, and it’s recommended to use canonicalize to get an absolute program path instead.

§Examples

Basic usage:

use wasi_net::Command;

Command::new("ls")
        .current_dir("/bin")
        .spawn()
        .expect("ls command failed to start");
Source

pub fn stdin(&mut self, cfg: Stdio) -> &mut Command

Configuration for the child process’s standard input (stdin) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

§Examples

Basic usage:

use wasi_net::{Command, Stdio};

Command::new("ls")
        .stdin(Stdio::null())
        .spawn()
        .expect("ls command failed to start");
Source

pub fn stdout(&mut self, cfg: Stdio) -> &mut Command

Configuration for the child process’s standard output (stdout) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

§Examples

Basic usage:

use std::process::{Command, Stdio};

Command::new("ls")
        .stdout(Stdio::null())
        .spawn()
        .expect("ls command failed to start");
Source

pub fn stderr(&mut self, cfg: Stdio) -> &mut Command

Configuration for the child process’s standard error (stderr) handle.

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

§Examples

Basic usage:

use std::process::{Command, Stdio};

Command::new("ls")
        .stderr(Stdio::null())
        .spawn()
        .expect("ls command failed to start");
Source

pub fn pre_open(&mut self, path: String) -> &mut Command

Pre-opens a directory before launching the process

Source

pub fn spawn(&self) -> Result<Child>

Executes the command as a child process, returning a handle to it.

By default, stdin, stdout and stderr are inherited from the parent.

§Examples

Basic usage:

use wasi_net::Command;

Command::new("ls")
        .spawn()
        .expect("ls command failed to start");
Source

pub fn output(&mut self) -> Result<Output>

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

By default, stdout and stderr are captured (and used to provide the resulting output). Stdin is not inherited from the parent and any attempt by the child process to read from the stdin stream will result in the stream immediately closing.

§Examples
use wasi_net::Command;
use std::io::{self, Write};
let output = Command::new("/bin/cat")
                     .arg("file.txt")
                     .output()
                     .expect("failed to execute process");

println!("status: {}", output.status);
io::stdout().write_all(&output.stdout).unwrap();
io::stderr().write_all(&output.stderr).unwrap();

assert!(output.status.success());
Source

pub fn status(&mut self) -> Result<ExitStatus>

Executes a command as a child process, waiting for it to finish and collecting its status.

By default, stdin, stdout and stderr are inherited from the parent.

§Examples
use wasi_net::Command;

let status = Command::new("/bin/cat")
                     .arg("file.txt")
                     .status()
                     .expect("failed to execute process");

println!("process finished with: {}", status);

assert!(status.success());

Trait Implementations§

Source§

impl Clone for Command

Source§

fn clone(&self) -> Command

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Command

Source§

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

Formats the value using the given formatter. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

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