问题:
def tradingview():是一个infite循环,它应该返回两个数字
def tradingview():
while True:
with open(filepath, 'r') as f:
count_var_short = f.read().count('Exit Short Open')
print('Current shorts open:',count_var_short)
with open(filepath, 'r') as f:
count_var_long = f.read().count('Exit Long Open')
print('Current longs open:',count_var_long)
return (count_var_short,count_var_long)
def target_balance(count_var_short,count_var_long):
current_target = cur_price_VWAP['vwap'] * freebalance['BTC']['free']
print ('current_target long',current_target * count_var_short)
print ('current_target short',current_target * count_var_long)
if __name__ == '__main__':
Thread(target = tradingview).start()
Thread(target = target_balance(count_var_short,count_var_long)).start()
此代码提供错误
Thread(target = target_balance(count_var_short,count_var_long)).start()
NameError: name 'count_var_short' is not defined
===============================================
我希望def tradingview():
返回两个数字
count_var_short
和count_var_long
并在功能中使用它们
def target_balance(count_var_short,count_var_long):
我知道我应该阅读返回的工作原理,但如果有人帮我编写自己的代码,我会非常感激,因为这对我来说更容易理解。
答案 0 :(得分:3)
而不是具有单个返回值的函数,您希望创建一个生成器,yield
是一个表达式,然后继续执行。
您可以将tradingview
重写为无限生成器:
def tradingview():
while True:
with open(filepath, 'r') as f:
count_var_short = f.read().count('Exit Short Open')
print('Current shorts open:',count_var_short)
with open(filepath, 'r') as f:
count_var_long = f.read().count('Exit Long Open')
print('Current longs open:',count_var_long)
yield count_var_short, count_var_long
循环中的yield
表达式 循环将在恢复执行之前“返回”您想要的值。它还会将tradingview
从常规函数转换为生成函数,该函数在调用时返回生成器。
现在您可以重写调用target_balance
的代码来使用生成器:
if __name__ == '__main__':
for count_var_short, count_var_long in tradingview():
target_balance(count_var_short,count_var_long)
不需要奇怪的线程行为:Python已经提供了生成器所需的行为。我建议您仔细阅读它们(以及yield
关键字)。