2017-08-24 37 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