简体   繁体   中英

How do I start a terminal instance from a compiled rust executable?

I am making a small-scale project which reads from a file of 101 items, creates a vector of strings, and then randomly accesses one of the items and prints it to the standard output. The program works exactly as intended when run from the terminal, whether through cargo run or by running the executable from the terminal with ./executable_name . The problem is, if I double click on the executable without a terminal open there is nowhere for the information to be printed and the program is essentially useless. I know how to check if a terminal is open using

if atty::is(Stream::Stdout) {
    println!("Already in terminal");
    } else {
    // this is where I get confused
    }   

but from there I don't know where to go. I have experimented with things like Command::new("sh"); but am struggling with the documentation. Eventually, the idea is that I can compile this on my partners Mac without losing its functionality as I am writing it on Linux, and create an easy to use application to run it on her machine.

Programs generally do not open their own terminal windows. The way you arrange for one to exist varies by platform:

  • On macOS, you actually don't have to do anything; the default behavior of double-clicking an executable is to open a terminal to run it in. (GUI applications have their executables inside of .app packages so that this behavior does not apply to them.)

  • On Windows, whether a terminal is opened is a property of the executable, which you can set in Rust with the windows_subsystem attribute . However, the default value is console so you don't need to do anything.

  • On Linux, you'd create a .desktop file that specifies Terminal=true , to ask the desktop environment to launch your program in a terminal, and double-click that file rather than the executable. Or, you could make your program launch a terminal emulator and instruct it to start your program again within itself, but how you do that will depend on what terminal emulator programs are installed.

The one thing you'll have to do for all these cases is add a “Press Enter to exit” prompt to your program. Otherwise, the terminal will close immediately after your program exits, and so your output won't be visible.

eprintln!("Press Enter to exit.");
std::io::stdin().read_line(&mut String::new()).unwrap();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM