簡體   English   中英

如果失去互聯網連接,如何重置python程序

[英]How do I reset a python program in the event of internet connection lost

好的,所以我有這個用Python編寫並在Python 2.7上運行的程序,用於與BTC進行交易。 在編程方面,我是一個新手,但是我對如何調整機器人並為其創建規則非常了解。 它運行良好,直到互聯網連接發生變化,即我打開/關閉VPN。 我想知道在“無法獲得響應”的情況下可以使用什么代碼來重新啟動程序? 您的幫助將不勝感激。 這是用於啟動程序和主循環的代碼。

def loop_body(self):  
        orders = self.update_portfolio()
        if orders is None:
            return

        if self.get_num_open_bids(orders) + self.get_num_open_asks(orders) >= MAX_OPEN_ORDERS and REMOVE_UNREALISTIC:
            self.update_portfolio

        if self.get_num_open_bids(orders) + self.get_num_open_asks(orders) >= MAX_OPEN_ORDERS:
            if DEBUG_MODE:
                print '---'
                print 'Too many open orders, sleep for', TOO_MANY_OPEN_SLEEP, 'seconds.'
                print " "
                print 'I have', self.get_num_portfolio_bids(), 'open bids,', self.get_num_portfolio_asks(), 'asks.'
                print 'API shows', self.get_num_open_bids(orders), 'open bids,', self.get_num_open_asks(orders), 'asks.'
                print "---"
                print 'Profit :', self.profit, 'CNY'

            sleep(TOO_MANY_OPEN_SLEEP)
            return

        a = None
        b = None
        d = None
        e = None

        market_depth = self.get_market_depth()
        if not market_depth:
            return
        market_lowest_ask = self.get_lowest_market_ask(market_depth)
        a = market_lowest_ask
        market_highest_bid = self.get_highest_market_bid(market_depth)
        d = market_highest_bid
        sleep(5)

        market_depth = self.get_market_depth()
        if not market_depth:
            return
        market_lowest_ask = self.get_lowest_market_ask(market_depth)
        b = market_lowest_ask
        market_highest_bid = self.get_highest_market_bid(market_depth)
        e = market_highest_bid

        if DEBUG_MODE:
            print '---'
            print 'I have', self.get_num_portfolio_bids(), 'open bids,', self.get_num_portfolio_asks(), 'asks.'
            print 'API shows', self.get_num_open_bids(orders), 'open bids,', self.get_num_open_asks(orders), 'asks.'
            print "---"
            print 'Profit :', self.profit, 'CNY'

        my_ask_price_2 = market_lowest_ask - CNY_STEP
        my_bid_price_2 = my_ask_price_2 - MIN_SURPLUS

        if a > b and d > e:
            for trial in xrange(MAX_TRIAL):
                response = self.trader.sell('{0:.2f}'.format(my_ask_price_2), BTC_AMOUNT)
                if response is True:
                    self.portfolio.append(
                        {'bid': my_bid_price_2, 'ask': my_ask_price_2, 'status': 'sell'})
                    if DEBUG_MODE:
                        print "---"
                        print 'I sold', BTC_AMOUNT, 'bitcoins at', my_ask_price_2
                    break
                else:
                    if DEBUG_MODE:
                        print "---"
                        print 'Sell failed:', response
                    break
                break

        my_bid_price = market_highest_bid + CNY_STEP
        my_ask_price = my_bid_price + MIN_SURPLUS 

        if a < b and d < e:
            for trial in xrange(MAX_TRIAL):
                if self.trader.buy('{0:.2f}'.format(my_bid_price), BTC_AMOUNT):
                    self.portfolio.append(
                        {'bid': my_bid_price, 'ask': my_ask_price, 'status': 'buy'})
                    if DEBUG_MODE:
                        print "---"
                        print 'I bought', BTC_AMOUNT, 'bitcoins at', my_bid_price
                    break
                else:
                    if DEBUG_MODE:
                        print "---"
                        print 'Buy failed:', response
                    break
                break

    def start(self):
        self.reset()
        while True:
            self.loop_body()

if __name__ == '__main__':
    bot = Bot()
    bot.start()

最好只管理您的Internet交易並檢查請求是否超時。 然后適當處理這種情況-睡覺,再試一次,等等。

如果要定期重新啟動python程序,則可能需要第二個腳本或Shell腳本,但這並不是處理這種情況的正確方法。

您需要在這里做兩件事。

首先,大概是您所指的“失敗的響應事件”是任何Bot庫拋出的異常。 因此,您需要以某種方式處理該異常。

其次,您需要一個永久循環的while循環,將所有內容包裹起來,因此在處理異常之后,您將返回頂部並重試。


如果您使用的是Windows以外的任何平台,並且您不介意每次連接斷開時都打印出丑陋的異常回溯,那么在包裝Shell腳本中這樣做可能會更容易:

#!/bin/sh

while true; do
    python ./myscript.py
done

無論程序是正常退出還是由於異常退出,您的Shell腳本都將再次循環。


如果要在Python中執行此操作,則可以將頂級代碼更改為:

if __name__ == '__main__':
    while True:
        try:
            bot = Bot()
            bot.start()
        except Exception as e:
            print('Failed with {!r}, retrying', e)

如果您實際上知道要獲取的特定異常-如果它不在您的原始回溯中,它將是新循環中e的類型-您可能只想處理該異常。 這樣,如果您的程序存在其他問題,則不會永遠循環,而是向您顯示出問題所在。 (沒有什么比輸入錯誤引起無限循環的Failed with NameError: 'slef'消息更糟糕了...)。一旦知道,就將except行更改為:

except LostConnectionException as e:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM