【问题标题】:Is there a way to automate a program to fill in commands in the terminal on pycharm?有没有办法自动化程序来在 pycharm 上的终端中填写命令?
【发布时间】:2021-08-15 20:06:51
【问题描述】:

我正在使用 pycharm 中的 spotify-cli,我希望能够自动化程序(因为这只是较长程序的一小部分),以便它可以选择 spotify 搜索命令的第一首歌曲拉起。我目前有这个作为代码:

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

这就是终端中显示的内容(例如你属于我):

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
: 

所以我的代码提示搜索结果的第一部分有效,但我的程序不会继续到下一行代码,除非我手动输入“p 1”并将其余提示输入终端。我已经看到了 pexpect 可能为此工作的可能性,但是如果我的歌曲搜索结果总是在变化,我是否能够为此编写代码?我也是编码新手,所以任何建议或简单的解释都将不胜感激。谢谢!

【问题讨论】:

    标签: python spotify


    【解决方案1】:

    你可以使用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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2019-10-12
      相关资源
      最近更新 更多