Struct subprocess::Exec[][src]

#[must_use]
pub struct Exec { /* fields omitted */ }
Expand description

A builder for Popen instances, providing control and convenience methods.

Exec provides a builder API for Popen::create, and includes convenience methods for capturing the output, and for connecting subprocesses into pipelines.

Examples

Execute an external command and wait for it to complete:

let exit_status = Exec::cmd("umount").arg(dirname).join()?;

Execute the command using the OS shell, like C’s system:

Exec::shell("shutdown -h now").join()?;

Start a subprocess and obtain its output as a Read trait object, like C’s popen:

let stream = Exec::cmd("ls").stream_stdout()?;
// call stream.read_to_string, construct io::BufReader(stream), etc.

Capture the output of a command:

let out = Exec::cmd("ls")
  .stdout(Redirection::Pipe)
  .capture()?
  .stdout_str();

Redirect errors to standard output, and capture both in a single stream:

let out_and_err = Exec::cmd("ls")
  .stdout(Redirection::Pipe)
  .stderr(Redirection::Merge)
  .capture()?
  .stdout_str();

Provide input to the command and read its output:

let out = Exec::cmd("sort")
  .stdin("b\nc\na\n")
  .stdout(Redirection::Pipe)
  .capture()?
  .stdout_str();
assert!(out == "a\nb\nc\n");

Implementations

impl Exec[src]

pub fn cmd(command: impl AsRef<OsStr>) -> Exec[src]

Constructs a new Exec, configured to run command.

The command will be run directly in the OS, without an intervening shell. To run it through a shell, use Exec::shell instead.

By default, the command will be run without arguments, and none of the standard streams will be modified.

pub fn shell(cmdstr: impl AsRef<OsStr>) -> Exec[src]

Constructs a new Exec, configured to run cmdstr with the system shell.

subprocess never spawns shells without an explicit request. This command requests the shell to be used; on Unix-like systems, this is equivalent to Exec::cmd("sh").arg("-c").arg(cmdstr). On Windows, it runs Exec::cmd("cmd.exe").arg("/c").

shell is useful for porting code that uses the C system function, which also spawns a shell.

When invoking this function, be careful not to interpolate arguments into the string run by the shell, such as Exec::shell(format!("sort {}", filename)). Such code is prone to errors and, if filename comes from an untrusted source, to shell injection attacks. Instead, use Exec::cmd("sort").arg(filename).

pub fn arg(self, arg: impl AsRef<OsStr>) -> Exec[src]

Appends arg to argument list.

pub fn args(self, args: &[impl AsRef<OsStr>]) -> Exec[src]

Extends the argument list with args.

pub fn detached(self) -> Exec[src]

Specifies that the process is initially detached.

A detached process means that we will not wait for the process to finish when the object that owns it goes out of scope.

pub fn env_clear(self) -> Exec[src]

Clears the environment of the subprocess.

When this is invoked, the subprocess will not inherit the environment of this process.

pub fn env(self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Exec[src]

Sets an environment variable in the child process.

If the same variable is set more than once, the last value is used.

Other environment variables are by default inherited from the current process. If this is undesirable, call env_clear first.

pub fn env_extend(self, vars: &[(impl AsRef<OsStr>, impl AsRef<OsStr>)]) -> Exec[src]

Sets multiple environment variables in the child process.

The keys and values of the variables are specified by the slice. If the same variable is set more than once, the last value is used.

Other environment variables are by default inherited from the current process. If this is undesirable, call env_clear first.

pub fn env_remove(self, key: impl AsRef<OsStr>) -> Exec[src]

Removes an environment variable from the child process.

Other environment variables are inherited by default.

pub fn cwd(self, dir: impl AsRef<Path>) -> Exec[src]

Specifies the current working directory of the child process.

If unspecified, the current working directory is inherited from the parent.

pub fn stdin(self, stdin: impl Into<InputRedirection>) -> Exec[src]

Specifies how to set up the standard input of the child process.

Argument can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file);
  • a Vec<u8> or &str, which will set up a Redirection::Pipe for stdin, making sure that capture feeds that data into the standard input of the subprocess;
  • NullFile, which will redirect the standard input to read from /dev/null.

pub fn stdout(self, stdout: impl Into<OutputRedirection>) -> Exec[src]

Specifies how to set up the standard output of the child process.

Argument can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file);
  • NullFile, which will redirect the standard output to go to /dev/null.

pub fn stderr(self, stderr: impl Into<OutputRedirection>) -> Exec[src]

Specifies how to set up the standard error of the child process.

Argument can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file);
  • NullFile, which will redirect the standard error to go to /dev/null.

pub fn popen(self) -> PopenResult<Popen>[src]

Starts the process, returning a Popen for the running process.

pub fn join(self) -> PopenResult<ExitStatus>[src]

Starts the process, waits for it to finish, and returns the exit status.

This method will wait for as long as necessary for the process to finish. If a timeout is needed, use <...>.detached().popen()?.wait_timeout(...) instead.

pub fn stream_stdout(self) -> PopenResult<impl Read>[src]

Starts the process and returns a value implementing the Read trait that reads from the standard output of the child process.

This will automatically set up stdout(Redirection::Pipe), so it is not necessary to do that beforehand.

When the trait object is dropped, it will wait for the process to finish. If this is undesirable, use detached().

pub fn stream_stderr(self) -> PopenResult<impl Read>[src]

Starts the process and returns a value implementing the Read trait that reads from the standard error of the child process.

This will automatically set up stderr(Redirection::Pipe), so it is not necessary to do that beforehand.

When the trait object is dropped, it will wait for the process to finish. If this is undesirable, use detached().

pub fn stream_stdin(self) -> PopenResult<impl Write>[src]

Starts the process and returns a value implementing the Write trait that writes to the standard input of the child process.

This will automatically set up stdin(Redirection::Pipe), so it is not necessary to do that beforehand.

When the trait object is dropped, it will wait for the process to finish. If this is undesirable, use detached().

pub fn communicate(self) -> PopenResult<Communicator>[src]

Starts the process and returns a Communicator handle.

This is a lower-level API that offers more choice in how communication is performed, such as read size limit and timeout, equivalent to Popen::communicate.

Unlike capture(), this method doesn’t wait for the process to finish, effectively detaching it.

pub fn capture(self) -> PopenResult<CaptureData>[src]

Starts the process, collects its output, and waits for it to finish.

The return value provides the standard output and standard error as bytes or optionally strings, as well as the exit status.

Unlike Popen::communicate, this method actually waits for the process to finish, rather than simply waiting for its standard streams to close. If this is undesirable, use detached().

pub fn to_cmdline_lossy(&self) -> String[src]

Show Exec as command-line string quoted in the Unix style.

Trait Implementations

impl BitOr<Exec> for Exec[src]

fn bitor(self, rhs: Exec) -> Pipeline[src]

Create a Pipeline from self and rhs.

type Output = Pipeline

The resulting type after applying the | operator.

impl BitOr<Exec> for Pipeline[src]

fn bitor(self, rhs: Exec) -> Pipeline[src]

Append a command to the pipeline and return a new pipeline.

type Output = Pipeline

The resulting type after applying the | operator.

impl Clone for Exec[src]

fn clone(&self) -> Exec[src]

Returns a copy of the value.

This method is guaranteed not to fail as long as none of the Redirection values contain a Redirection::File variant. If a redirection to File is present, cloning that field will use File::try_clone method, which duplicates a file descriptor and can (but is not likely to) fail. In that scenario, Exec::clone panics.

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl Debug for Exec[src]

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

Formats the value using the given formatter. Read more

Auto Trait Implementations

impl !RefUnwindSafe for Exec

impl !Send for Exec

impl !Sync for Exec

impl Unpin for Exec

impl UnwindSafe for Exec

Blanket Implementations

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

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

Gets the TypeId of self. Read more

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

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

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

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

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

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

Performs the conversion.

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

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

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

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

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

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.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[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.

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

Performs the conversion.