Is there a way to automate a program to fill in commands in the terminal on pycharm?

Viewed 48

I'm playing around with spotify-cli in pycharm and I want to be able to automate the program (since this is just a small piece of a longer program) so that it can choose the first song that the spotify search command pulls up. I currently have this as the code:

song = input(pick a song: )
os.system("spotify search " + song)
os.system("p 1")
os.system("y")
os.system("n")

And this is what shows up in the terminal (example is you belong with me):

pick a song: you belong with me

Search results for "you belong with me"

  #  Track                                    Artist
---  ---------------------------------------  ----------------------
  1  You Belong With Me                       Taylor Swift
  2  Ho Hey                                   The Lumineers
  3  You Belong With Me                       For All Those Sleeping
  4  You Belong With Me (Taylor’s Version)    Taylor Swift
  5  You Belong With Me                       Taylor Swift
  6  You Belong With Me (Remix)               Remixed Factory
  7  You Belong With Me (Piano Instrumental)  Minnz Piano
  8  You Belong With Me                       Taylor Swift
  9  You Belong With Me                       Kidz Bop Kids
 10  Eternal Flame                            The Bangles

Actions:
[n]ext/[b]ack
[p]lay/[q]ueue/[s]ave #[,...]
[Ctrl+C] exit
: 

So the first part part where my code prompts for search results works, but my program won't continue onto the next line of code unless I manually enter in "p 1" and the rest of the prompts into the terminal. I have seen a possibility of pexpect possibly working for this, but will I be able to code for that if my song search results are always changing? I am also new to coding, so any advice or dummied down explanations would be appreciated. Thanks!

1 Answers

You can use subprocess.Popen:

import subprocess

song = input("Pick a song: ")
process = subprocess.Popen(["spotify", "search", song], stdout=subprocess.PIPE, 
                           stdin=subprocess.PIPE, stderr=subprocess.PIPE)

process.stdin.write("p 1")
process.stdin.write("y")
process.stdin.write("n")
Related