Error external script, strange behavior

Hi, this python script generate a list.html from directory. and execute FINE in shell:
pichi@mypc:/python3 /home/pichi/LinuxDir2HTML-master/linuxdir2html/linuxdir2html.py /home/pichi/AAA/ /home/pichi/html/list

this means:
root to script python -> /home/pichi/LinuxDir2HTML-master/linuxdir2html/linuxdir2html.py
directory source to index(arg) -> /home/pichi/AAA/
destiny(arg) -> /home/pichi/html/list

code rust error:

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

    // .var to store result
    let mut dir_src = String::new();
    let dir_dst = "/home/pichi/html/list".to_string();
    
    // reading source from terminal
    let stdin_dir_src = io::stdin();
    stdin_dir_src.read_line(&mut dir_src).unwrap();
    
    // execute command
    let output = Command::new("python3")
                    .arg("/home/pichi/LinuxDir2HTML-master/linuxdir2html/linuxdir2html.py")
                    .arg(&dir_src) // dir_src
                    .arg(&dir_dst) // dir_dst                
                    .output()
                    .expect("Error command..");
    
    println!("status: {}", String::from_utf8_lossy(&output.stderr));

RUST OUTPUT ERROR:
status: 21:49:16 Directory specified to index [/home/pichi/AAA
] doesn't exist. Aborting.

NOTE: when i change let dir_src = "/home/pichi/AAA".to_string();
works fine.

You're not trimming dir_src, so it contains the newline from pressing enter. Instead of

/home/pichi/AAA

it tries to open

/home/pichi/AAA

which is why the error looks like

 status: 21:49:16 Directory specified to index [/home/pichi/AAA
] doesn't exist. Aborting.

instead of

 status: 21:49:16 Directory specified to index [/home/pichi/AAA] doesn't exist. Aborting.

This is also why "/home/pichi/AAA".to_string() works, since it doesn't contain a newline at the end.

I recommend something like

let mut buffer = String::new();
io::stdin().read_line(&mut buffer).unwrap();
let dir_src = buffer.trim();

Naming the variable buffer instead of dir_src helps make it more clear that it's just the string you're reading input into. (See the docs for trim here: str - Rust)

3 Likes

thank you so much :face_holding_back_tears:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.