a e
a e

Reputation: 33

Use variables as command arguments

In a program I am trying to display the artwork of my currently playing spotify song using rust.

The code only works if I copy and paste the url into the argument, so I tried making a variable called arturl to use in a .arg(arturl). But that makes the code return nothing, and the arturl variable does return the correct value.

My code:

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

fn main() {
    let arturl = Command::new("playerctl")
        .arg("metadata")
        .arg("mpris:artUrl")
        .stdout(Stdio::piped())
        .output()
        .expect("url failed");
    let arturl = String::from_utf8(arturl.stdout).unwrap();

    let picture = Command::new("chafa")
        .arg("--size=30")
        .arg(arturl)
        .stdout(Stdio::piped())
        .output()
        .expect("picture failed");
    let picture = String::from_utf8(picture.stdout).unwrap();
    println!("{}", picture);
}

Upvotes: 0

Views: 688

Answers (2)

Netwave
Netwave

Reputation: 42688

You should probably "clean" the string with str::trim:

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

fn main() {
    let arturl = Command::new("playerctl")
        .arg("metadata")
        .arg("mpris:artUrl")
        .stdout(Stdio::piped())
        .output()
        .expect("url failed");
    let arturl = String::from_utf8(arturl.stdout).unwrap().trim();
    println!("{:?}", arturl);

    let picture = Command::new("chafa")
        .arg("--size=30")
        .arg(arturl)
        .stdout(Stdio::piped())
        .output()
        .expect("picture failed");
    let picture = String::from_utf8(picture.stdout).unwrap();
    println!("{}", picture);
}

Upvotes: 1

a e
a e

Reputation: 33

Managed to fixed this with adding a simple arturl.pop to get rid of the newline at the end of the string

fixed code:

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

fn main() {
    let arturl = Command::new("playerctl")
        .arg("metadata")
        .arg("mpris:artUrl")
        .stdout(Stdio::piped())
        .output()
        .expect("url failed");
    let mut arturl = String::from_utf8(arturl.stdout).unwrap();
    arturl.pop();
    println!("{:?}", arturl);

    let picture = Command::new("chafa")
        .arg("--size=30")
        .arg(arturl)
        .stdout(Stdio::piped())
        .output()
        .expect("picture failed");
    let picture = String::from_utf8(picture.stdout).unwrap();
    println!("{}", picture);
}

Upvotes: 1

Related Questions