# 1.0.0[−][src]Struct std::process::Command

    pub struct Command { /* fields omitted */ }

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 std::process::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;Run

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

    use std::process::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");Run

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

    use std::process::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");

    println!("");

    // Change `ls` to execute in the root directory.
    list_dir.current_dir("/");

    // And then execute `ls` again but in the root directory.
    list_dir.status().expect("process failed to execute");Run

## Methods

### `impl Command`[src]

#### `pub fn new<S: AsRef<OsStr>>(program: S) -> Command`[src]

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.

The search path to be used may be controlled by setting the `PATH` environment variable on the Command, but this has some implementation limitations on Windows (see issue #37519).

# Examples

Basic usage:

    use std::process::Command;

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

#### `pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command`[src]

Adds an argument to pass to the program.

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

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

usage would be:

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

To pass multiple arguments see `args`.

# Examples

Basic usage:

    use std::process::Command;

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

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

Adds multiple arguments to pass to the program.

To pass a single argument see `arg`.

# Examples

Basic usage:

    use std::process::Command;

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

#### `pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command where
K: AsRef<OsStr>,
V: AsRef<OsStr>,` [src]

Inserts or updates an environment variable mapping.

Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms.

# Examples

Basic usage:

    use std::process::Command;

    Command::new("ls")
            .env("PATH", "/bin")
            .spawn()
            .expect("ls command failed to start");Run

#### `pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,` 1.19.0[src]

Adds or updates multiple environment variable mappings.

# Examples

Basic usage:

    use std::process::{Command, Stdio};
    use std::env;
    use std::collections::HashMap;

    let filtered_env : HashMap<String, String> =
        env::vars().filter(|&(ref k, _)|
            k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
        ).collect();

    Command::new("printenv")
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .env_clear()
            .envs(&filtered_env)
            .spawn()
            .expect("printenv failed to start");Run

#### `pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command`[src]

Removes an environment variable mapping.

# Examples

Basic usage:

    use std::process::Command;

    Command::new("ls")
            .env_remove("PATH")
            .spawn()
            .expect("ls command failed to start");Run

#### `pub fn env_clear(&mut self) -> &mut Command`[src]

Clears the entire environment map for the child process.

# Examples

Basic usage:

    use std::process::Command;

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

#### `pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command`[src]

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 std::process::Command;

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

#### `pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command`[src]

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 std::process::{Command, Stdio};

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

#### `pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command`[src]

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");Run

#### `pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command`[src]

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");Run

#### `pub fn spawn(&mut self) -> Result<Child>`[src]

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 std::process::Command;

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

#### `pub fn output(&mut self) -> Result<Output>`[src]

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 std::process::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());Run

#### `pub fn status(&mut self) -> Result<ExitStatus>`[src]

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

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

# Examples

    use std::process::Command;

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

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

    assert!(status.success());Run

## Trait Implementations

### `impl CommandExt for Command`[src]

#### `fn uid(&mut self, id: u32) -> &mut Command`[src]

This is supported on Unix only.

Sets the child process's user ID. This translates to a `setuid` call in the child process. Failure in the `setuid` call will cause the spawn to fail. Read more

#### `fn gid(&mut self, id: u32) -> &mut Command`[src]

This is supported on Unix only.

Similar to `uid`, but sets the group ID of the child process. This has the same semantics as the `uid` field. Read more

#### `unsafe fn pre_exec<F>(&mut self, f: F) -> &mut Command where
F: FnMut() -> Result<()> + Send + Sync + 'static,` [src]

This is supported on Unix only.

Schedules a closure to be run just before the `exec` function is invoked. Read more

#### `fn exec(&mut self) -> Error`[src]

This is supported on Unix only.

Performs all the required setup by this `Command`, followed by calling the `execvp` syscall. Read more

#### `fn before_exec<F>(&mut self, f: F) -> &mut Command where
F: FnMut() -> Result<()> + Send + Sync + 'static,` 1.15.0[src]

Deprecated since 1.37.0:

should be unsafe, use `pre_exec` instead

This is supported on Unix only.

Schedules a closure to be run just before the `exec` function is invoked. Read more

### `impl CommandExt for Command` 1.16.0[src]

#### `fn creation_flags(&mut self, flags: u32) -> &mut Command`[src]

This is supported on Windows only.

Sets the [process creation flags][1] to be passed to `CreateProcess`. Read more

### `impl Debug for Command`[src]

#### `fn fmt(&self, f: &mut Formatter) -> Result`[src]

Format the program and arguments of a Command for display. Any non-utf8 data is lossily converted using the utf8 replacement character.

## Auto Trait Implementations

### `impl !UnwindSafe for Command`

### `impl !RefUnwindSafe for Command`

### `impl Unpin for Command`

### `impl !Sync for Command`

### `impl Send for Command`

## Blanket Implementations

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>`[src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `fn into(self) -> U`[src]

Performs the conversion.

### `impl<T> From<T> for T`[src]

#### `fn from(t: T) -> T`[src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

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

The type returned in the event of a conversion error.

#### `fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>`[src]

Performs the conversion.

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

####
ⓘImportant traits for &'_ mut I

### Important traits for &'_ mut I

`impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;impl<'_, R: Read + ?Sized> Read for &'_ mut Rimpl<'_, W: Write + ?Sized> Write for &'_ mut W`
`fn borrow(&self) -> &T`[src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

####
ⓘImportant traits for &'_ mut I

### Important traits for &'_ mut I

`impl<'_, I> Iterator for &'_ mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;impl<'_, R: Read + ?Sized> Read for &'_ mut Rimpl<'_, W: Write + ?Sized> Write for &'_ mut W`
`fn borrow_mut(&mut self) -> &mut T`[src]

Mutably borrows from an owned value. Read more

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `fn type_id(&self) -> TypeId`[src]

Gets the `TypeId` of `self`. Read more

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)