如果互联网连接丢失,如何重置python程序

时间:2014-08-15 00:03:01

标签: python

好的,所以我用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()

2 个答案:

答案 0 :(得分:0)

最好管理您的互联网交易并检查请求是否超时。然后适当处理这种情况 - 睡觉,再试一次等​​等。

如果你想定期重启一个python程序,你可能需要第二个脚本或shell脚本,但这并不是处理这种情况的正确方法。

答案 1 :(得分:0)

你需要做两件事。

首先,大概是'事件'未能获得响应''你所指的是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: