简体   繁体   English

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

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

Ok, so I have this program written in Python and running on Python 2.7 that I use to trade BTC with. 好的,所以我有这个用Python编写并在Python 2.7上运行的程序,用于与BTC进行交易。 I am a complete novice when it comes to programing, but I know enough on how to tweak the bot and create rules for it. 在编程方面,我是一个新手,但是我对如何调整机器人并为其创建规则非常了解。 It runs fine until there is a change of internet connection ie I trun on/off my VPN. 它运行良好,直到互联网连接发生变化,即我打开/关闭VPN。 I would like to know what code can I use to restart the program in the event of "Failed to get response"? 我想知道在“无法获得响应”的情况下可以使用什么代码来重新启动程序? Your help would be appreciated. 您的帮助将不胜感激。 Here is the code used to launch the program and the main loop. 这是用于启动程序和主循环的代码。

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()

It's better to just manage your internet transactions and check to see if requests time out. 最好只管理您的Internet交易并检查请求是否超时。 Then handle the situation appropriately -- sleep, try again, etc. 然后适当处理这种情况-睡觉,再试一次,等等。

If you want to restart a python program periodically, you probably need a second script or a shell script, but that's not really the right way to handle this situation. 如果要定期重新启动python程序,则可能需要第二个脚本或Shell脚本,但这并不是处理这种情况的正确方法。

There's two things you need to do here. 您需要在这里做两件事。

First, presumably that 'event of "Failed to get response"' you're referring to is an exception thrown by whatever that Bot library is. 首先,大概是您所指的“失败的响应事件”是任何Bot库抛出的异常。 So, you need to handle that exception in some way. 因此,您需要以某种方式处理该异常。

Second, you need a loop-forever while loop wrapped around everything, so after you handle the exception, you go back to the top and try again. 其次,您需要一个永久循环的while循环,将所有内容包裹起来,因此在处理异常之后,您将返回顶部并重试。


If you're on any platform but Windows, and you don't mind ugly exception tracebacks being printed out every time there's a lost connection, this might be easier to do in a wrapper shell script: 如果您使用的是Windows以外的任何平台,并且您不介意每次连接断开时都打印出丑陋的异常回溯,那么在包装Shell脚本中这样做可能会更容易:

#!/bin/sh

while true; do
    python ./myscript.py
done

Whether the program exits normally or quits because of an exception, your shell script will just go through the loop again. 无论程序是正常退出还是由于异常退出,您的Shell脚本都将再次循环。


If you want to do this in Python, you can change your top-level code to: 如果要在Python中执行此操作,则可以将顶级代码更改为:

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

If you actually know the particular exception you're getting—if it wasn't in your original tracebacks, it'll be the type of e in the new loop—you may want to handle just that exception. 如果您实际上知道要获取的特定异常-如果它不在您的原始回溯中,它将是新循环中e的类型-您可能只想处理该异常。 That way, if there's something else wrong with your program, instead of looping forever, it'll show you what went wrong. 这样,如果您的程序存在其他问题,则不会永远循环,而是向您显示出问题所在。 (There's nothing worse than a typo causing an infinite loop of Failed with NameError: 'slef' messages…) Once you know it, just change the except line to: (没有什么比输入错误引起无限循环的Failed with NameError: 'slef'消息更糟糕了...)。一旦知道,就将except行更改为:

except LostConnectionException as e:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM