'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);
}
Solution 1:[1]
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);
}
Solution 2:[2]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Netwave |
| Solution 2 | a e |
