Advertisement
Valeria_Fadeeva

run external process

Jan 18th, 2022 (edited)
51
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::process::{Command, Stdio};
  2. use std::{env, fs, str};
  3.  
  4. fn read_file(watch_path: &str) -> String {
  5.     let filepath: String;
  6.  
  7.     let filepath_r = fs::read_to_string(watch_path);
  8.     filepath = match filepath_r {
  9.         Ok(filepath) => filepath,
  10.         Err(error) => {
  11.             panic!("Problem opening the file: {:?}", error)
  12.         }
  13.     };
  14.  
  15.     return filepath;
  16. }
  17.  
  18. fn main() {
  19.     let args: Vec<String> = env::args().collect();
  20.  
  21.     let python_path = ".env";
  22.     let p = read_file(python_path);
  23.  
  24.     let app: &str = if cfg!(target_os = "windows") {
  25.         &*p.trim()
  26.     } else if cfg!(target_os = "linux") {
  27.         "python3"
  28.     } else {
  29.         "python3"
  30.     };
  31.  
  32.     let execute = "mock-command.py";
  33.  
  34.     let child = if args.len() == 1 {
  35.         Command::new(app)
  36.             .args([execute])
  37.             .stderr(Stdio::null()) // don't care about stderr
  38.             .stdout(Stdio::inherit()) // set up stdout so we can read it
  39.             .stdin(Stdio::inherit()) // set up stdin so we can write on it
  40.             .spawn()
  41.             .expect("Could not run the command") // finally run the command
  42.     } else {
  43.         Command::new(app)
  44.             .args([execute, &args[1]])
  45.             .stderr(Stdio::null()) // don't care about stderr
  46.             .stdout(Stdio::inherit()) // set up stdout so we can read it
  47.             .stdin(Stdio::inherit()) // set up stdin so we can write on it
  48.             .spawn()
  49.             .expect("Could not run the command") // finally run the command
  50.     };
  51.  
  52.     let output = child.wait_with_output().expect("Failed to wait on child");
  53.  
  54.     let stdout = output.stdout.as_slice();
  55.     let out = str::from_utf8(&stdout).unwrap();
  56.  
  57.     println!("{}", out);
  58. }
  59.  
Advertisement
RAW Paste Data Copied
Advertisement