【问题标题】:How to print only if X amount of time has elapsed仅在 X 时间已过时如何打印
【发布时间】:2015-01-08 22:56:28
【问题描述】:

我目前有一个脚本,它可以解析来自 iTunes 的有关当前正在播放的歌曲的信息并打印出来。它仅在歌曲更改时打印。现在我想让它只在歌曲的一分钟过去后才打印出来,但不知道该怎么做。

这是我目前拥有的代码:

def giveData():
    last_title, last_artist, last_album = None, None, None
    while True:
       template = '"%s" by %s (%d)\n from %s'
       info = ''

iTunesCount = app('System Events').processes[its.name == 'iTunes'].count()
if iTunesCount > 0:
  iTunes = app('iTunes')
  if iTunes.player_state.get() == k.playing:
    track = iTunes.current_track.get()
    artist = track.artist.get()
    title = track.name.get()
    album = track.album.get()
    stars = track.rating.get()/20

     if title != last_title or artist != last_artist or album != last_album:

      last_title, last_artist, last_album = title, artist, album
      info = template % (title, artist, stars, album)

    # Trying new solution, still printing songs that haven't been playing
    # for 60s, just delaying printing them by 60s:

      now = time.time()
      future = now + 60
      while time.time() < future:
        pass

      song_info = title + " - " + artist
      print song_info`

【问题讨论】:

  • 你使用的python库是什么?
  • 我使用的是 Python 2.7.8
  • 我们需要知道您是如何访问 iTunes 信息的。
  • 我正在使用 appscript,我将更新我的原始帖子。抱歉,这是我的第一篇文章,感谢您的耐心等待!
  • 你在哪里初始化last_titlelast_artistlast_album?你在哪里打电话giveData()?修正缩进...

标签: python itunes elapsedtime


【解决方案1】:

添加一个计时器怎么样?

import time

now = time.time()
future = now + 60
while time.time() < future:
    pass

print '60 seconds have passed'

或者正如@Undeterminant 指出的那样使用

time.sleep(60)

【讨论】:

  • 我现在更新了,以前的代码 prolly 不会工作 ;)
  • 我没有这样打印。也许我没有把声明放在正确的位置,现在它就在我原来帖子的评论位置。
  • 更新后的代码完美运行!非常感谢。
  • 我实际上又遇到了一些问题。它正在打印 60 秒未过的歌曲,只是将它们延迟打印 60 秒。也许我没有正确地写它。我会更新我原来的帖子。
  • 你刚刚实现了一个非常低效的time.sleep(1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 2016-01-23
  • 2016-07-12
  • 2015-12-06
  • 2021-05-07
相关资源
最近更新 更多