在Python3中,是否可以在特定函数之外附加代码行?
我正在尝试获取加密交换的订单簿,以了解如何支持特定的对,例如ETH/BTC。因为我的函数需要每分钟运行一次,所以每次检查都非常耗时。我在用ccxt取交易所的订单 我用这行代码检查每一次交换在Python3中,是否可以在特定函数之外附加代码行?,python,python-3.x,ccxt,Python,Python 3.x,Ccxt,我正在尝试获取加密交换的订单簿,以了解如何支持特定的对,例如ETH/BTC。因为我的函数需要每分钟运行一次,所以每次检查都非常耗时。我在用ccxt取交易所的订单 我用这行代码检查每一次交换 import ccxt binance = ccxt.binance() livecoin = ccxt.livecoin() kucoin = ccxt.kucoin() hitbtc = ccxt.hitbtc() kraken = ccxt.kraken() crex24
import ccxt
binance = ccxt.binance()
livecoin = ccxt.livecoin()
kucoin = ccxt.kucoin()
hitbtc = ccxt.hitbtc()
kraken = ccxt.kraken()
crex24 = ccxt.crex24()
okex = ccxt.okex()
headerList = ["time","type","pair"]
try:
orderbookBinance = binance.fetch_order_book(self.pair,5)
headerList.append("binance")
headerList.append("binanceAmount")
except:
print("Pair isn't available in binance")
try:
orderbookLivecoin = livecoin.fetch_order_book(self.pair,5)
headerList.append("livecoin")
headerList.append("livecoinAmount")
except:
print("Pair isn't available in livecoin")
try:
orderbookKucoin = kucoin.fetch_order_book(self.pair,5)
headerList.append("kucoin")
headerList.append("kucoinAmount")
except:
print("Pair isn't available in kucoin")
try:
orderbookHitbtc = hitbtc.fetch_order_book(self.pair,5)
headerList.append("hitbtc")
headerList.append("hitbtcAmount")
except:
print("Pair isn't available in hitbtc")
try:
orderbookKraken = kraken.fetch_order_book(self.pair,5)
headerList.append("kraken")
headerList.append("krakenAmount")
except:
print("Pair isn't available in kraken")
try:
orderbookCrex24 = crex24.fetch_order_book(self.pair,5)
headerList.append("crex24")
headerList.append("crex24Amount")
except:
print("Pair isn't available in crex24")
try:
orderbookOkex = okex.fetch_order_book(self.pair,5)
headerList.append("okex")
headerList.append("okexAmount")
except:
print("Pair isn't available in okex")
现在我需要添加所有try块的第一行,如果它们可以执行exetude。这在python中可能吗?您在这方面采取了错误的方法 代码行,就像变量名应该在程序中固定一样。 Python的超动态特性甚至允许添加代码行,并在运行时重新编译模块——但这将是复杂的、过度的、容易出错的,而您所需要的只是一种全新的方法 您需要的是将引用外部交换的对象保留在数据结构中,例如普通字典。然后,您只需在字典上进行迭代,以执行方法调用和每个调用所需的其他操作,程序的任何部分都可以使用简单、普通的属性更新字典
import ccxt
exchanges = {}
for exchange_name in "binance livecoin kucoin hitbtc kraken crex24 okex".split():
exchanges[exchange_name] = getattr(ccxt, exchange_name)()
...
for exchange_name, exchange in exchange.items():
try:
orderbook = exchange.fetch_order_book(self.pair,5)
headerList.append(exchange_name)
headerList.append(f"{exchange_name}Amount")
except:
print(f"Pair isn't available in {exchange_name}")
如果在某些交换的实际代码中需要运行不同的代码,只需改进数据结构:不必将交换名称直接与交换实例关联,您可以创建另一个内部字典,它将在其他键/值对中不仅包含ccxt交换实例,但是要调用的方法的名称、要传递给每个方法的参数、要在获得的响应中检查什么,等等:
程序中的代码已修复!它的一部分可以根据数据结构中的配置数据运行。现在我需要。。。我不明白。你能换个说法吗?另外,您应该创建一个元组列表[livecoin,livecoin,…],并为重复的try块创建一个函数。对不起,不清楚您要做什么。您可以尝试重新措辞吗?忘记密码的东西,试着把问题简化成一个两部分的问题,然后把这个解决方案应用到你的问题领域。。。