2017-08-24 62 views
1

我写了一个Python脚本来显示桌面通知,如果比特币的价格达到4500美元,但脚本将退出,如果价格已达到。我如何保持脚本运行?通知退出后致电

下面是代码:

import time 
import requests 
import gi 
gi.require_version('Notify', '0.7') 
from gi.repository import Notify 

r = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") 
r.json() 
resp = r.json() 

price = resp["bpi"]["USD"]["rate_float"] 
top = 4200 

if price > top : 

# One time initialization of libnotify 
Notify.init("Crypto Notify") 

# Create the notification object 
summary = "Crypto Alert!" 
body = "BTC : $ %s" % (price) 
notification = Notify.Notification.new(
    summary, 
    body, # Optional 
) 

# Actually show on screen 
notification.show() 

else: 
    while price < top : 
     r =requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") 
     print price 
time.sleep(10) 
+0

移动的'while'循环。如果您希望脚本永远运行(除非手动中断),请将其设置为'true:'。 – jonrsharpe

+0

所以它会:而真: r = ... ??我希望脚本能够永久运行并在价格达到后继续推送通知,这有可能吗? – Jordan

回答

0

因此,从我看到你好像剧本是写在单次即所有语句将被一次excuted执行。所以发生了什么事情是你的脚本等待价格更高的条件为真,一旦它是真的,它会执行IF块的其余脚本。

你需要的是封装脚本的循环和谁的结束条件将需要很长时间来实现一种无限循环,但更安全。

也是另一种方法,你可以尝试是保持脚本无限循环,只是当你想使用Ctrl + C

虽然它不是很干净的方式来做到这一点退出脚本。

示例代码:

import time 
import requests 
import gi 
gi.require_version('Notify', '0.7') 
from gi.repository import Notify 

while true : 
    r = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") 
    r.json() 
    resp = r.json() 

    price = resp["bpi"]["USD"]["rate_float"] 
    top = 4200 

    if price > top : 

    # One time initialization of libnotify 
    Notify.init("Crypto Notify") 

    # Create the notification object 
    summary = "Crypto Alert!" 
    body = "BTC : $ %s" % (price) 
    notification = Notify.Notification.new(summary,body) 

    # Actually show on screen 
    notification.show() 

    else: 
     r =requests.get("https://api.coindesk.com/v1/bpi/currentprice.json") 
     print price 
     time.sleep(10) 
+0

像编辑道歉,如果它从机场回答,因此无法测试一次不起作用。 – Ajay

+0

完美!它确实有效,我做了类似的等待您的答案!但是和澄清一样,它和你的一样“好”! – Jordan

+0

如果有帮助,您可以提出解答。 – Ajay