Skip to main content

Exec

Struct Exec 

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

A builder for creating subprocesses.

Exec provides a builder API for spawning subprocesses, 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 an impl Read, 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").capture()?.stdout_str();

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

let out_and_err = Exec::cmd("ls")
  .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")
  .capture()?
  .stdout_str();
assert!(out == "a\nb\nc\n");

Implementations§

Source§

impl Exec

Source

pub fn cmd(command: impl Into<OsString>) -> Exec

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.

Source

pub fn shell(cmdstr: impl Into<OsString>) -> Exec

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).

Source

pub fn arg(self, arg: impl Into<OsString>) -> Exec

Appends arg to argument list.

Source

pub fn args(self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Exec

Extends the argument list with args.

Source

pub fn detached(self) -> Exec

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.

Source

pub fn checked(self) -> Exec

If called, join and capture will return an error if the process exits with a non-zero status.

Source

pub fn env_clear(self) -> Exec

Clears the environment of the subprocess.

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

Source

pub fn env(self, key: impl Into<OsString>, value: impl Into<OsString>) -> Exec

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.

Source

pub fn env_extend( self, vars: impl IntoIterator<Item = (impl Into<OsString>, impl Into<OsString>)>, ) -> Exec

Sets multiple environment variables in the child process.

The keys and values of the variables are specified by the iterable. 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.

Source

pub fn env_remove(self, key: impl Into<OsString>) -> Exec

Removes an environment variable from the child process.

Other environment variables are inherited by default.

Source

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

Specifies the current working directory of the child process.

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

Source

pub fn stdin<T>(self, stdin: T) -> Exec
where InputRedirection: FromSource<T>,

Specifies the source for the standard input of the child process.

The source can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file);
  • a Vec<u8>, &str, &[u8], Box<[u8]>, or [u8; N], which will set up a Redirection::Pipe for stdin, feeding that data into the standard input of the subprocess;
  • an InputData, which also sets up a pipe, but wraps any reader and feeds its content to the standard input of the subprocess. Use InputData::from_bytes for in-memory byte containers not covered by the above, like bytes::Bytes or memmap2::Mmap. Use InputData::from_reader for a custom Read that generates or transforms data.

If the child exits before consuming all input, the BrokenPipe error is silently ignored. Use the exit status and output to check if the child processed the input correctly.

Source

pub fn stdout<T>(self, stdout: T) -> Exec

Specifies the sink for the standard output of the child process.

The sink can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file).
Source

pub fn stderr<T>(self, stderr: T) -> Exec

Specifies the sink for the standard error of the child process.

The sink can be:

  • a Redirection;
  • a File, which is a shorthand for Redirection::File(file).
Source

pub fn start(self) -> Result<Job>

Starts the process and returns a Job handle with the running process and its pipe ends.

Source

pub fn join(self) -> Result<ExitStatus>

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

Source

pub fn stream_stdout(self) -> Result<impl Read>

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().

§Panics

Panics if input data was specified with stdin. Use capture or communicate to both feed input and read output.

Source

pub fn stream_stderr(self) -> Result<impl Read>

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().

§Panics

Panics if input data was specified with stdin. Use capture or communicate to both feed input and read output.

Source

pub fn stream_stdin(self) -> Result<impl Write>

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().

§Panics

Panics if input data was specified with stdin.

Source

pub fn communicate(self) -> Result<Communicator>

Starts the process and returns a Communicator handle.

Unless already configured, stdout and stderr are redirected to pipes. If you need different redirection (e.g. stderr(Merge)), set it up before calling this method and it will be preserved.

Compared to capture(), this offers more choice in how communication is performed, such as read size limit and timeout. Unlike capture(), this method doesn’t wait for the process to finish, effectively detaching it.

Source

pub fn capture(self) -> Result<Capture>

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.

Unless already configured, stdout and stderr are redirected to pipes so they can be captured. If you need different redirection (e.g. stderr(Merge)), set it up before calling this method and it will be preserved.

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

Source

pub fn to_cmdline_lossy(&self) -> String

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

Trait Implementations§

Source§

impl BitOr<Exec> for Pipeline

Source§

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

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

Source§

type Output = Pipeline

The resulting type after applying the | operator.
Source§

impl BitOr for Exec

Source§

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

Create a Pipeline from self and rhs.

Source§

type Output = Pipeline

The resulting type after applying the | operator.
Source§

impl Debug for Exec

Source§

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

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

impl ExecExt for Exec

Source§

fn setuid(self, uid: u32) -> Exec

Set the user ID for the spawned process. Read more
Source§

fn setgid(self, gid: u32) -> Exec

Set the group ID for the spawned process. Read more
Source§

fn setpgid(self) -> Exec

Put the subprocess into its own process group. Read more
Source§

impl FromIterator<Exec> for Pipeline

Source§

fn from_iter<I: IntoIterator<Item = Exec>>(iter: I) -> Self

Creates a pipeline from an iterator of commands.

The iterator may yield any number of commands, including zero or one. An empty pipeline returns success on join() and empty output on capture(). A single-command pipeline behaves like running that command directly.

§Example
use subprocess::{Exec, Pipeline};

let commands = vec![
  Exec::shell("echo tset"),
  Exec::shell("tr '[:lower:]' '[:upper:]'"),
  Exec::shell("rev")
];

let pipeline: Pipeline = commands.into_iter().collect();
let output = pipeline.capture().unwrap().stdout_str();
assert_eq!(output, "TEST\n");

Auto Trait Implementations§

§

impl Freeze for Exec

§

impl !RefUnwindSafe for Exec

§

impl Send for Exec

§

impl Sync for Exec

§

impl Unpin for Exec

§

impl !UnwindSafe for Exec

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> 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, 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.