【问题标题】:Python return values from one function to another in infinite loopPython在无限循环中将值从一个函数返回到另一个函数
【发布时间】:2018-04-02 11:55:07
【问题描述】:

问题:

def 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)                           
        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_shortcount_var_long

并在函数中使用它们

def target_balance(count_var_short,count_var_long):

我知道我应该阅读 return 的工作原理,但如果有人帮助我编写我自己的代码,我将非常感激,因为它对我来说更容易理解。

【问题讨论】:

  • 为什么要创建线程来执行函数?你明白在第一个函数完成之前你不能有返回值吗?这里发生了什么?
  • 为什么我看到一个没有任何退出或中断语句的while True 循环?你想要那个无限循环吗?程序永远不会到达return 语句。
  • 另外,请不要链接到站外代码。这就是最小可重现示例的全部意义。
  • @KeyurPotdar。我什至没有看那么远。这实际上回答了我的问题。
  • def tradingview(): 是无限循环,应该返回两个数字

标签: python function return infinite-loop


【解决方案1】:

您希望创建一个生成器,而不是具有单个返回值的函数,它yields 是一个表达式,然后继续执行。

您可以将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 关键字)。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2019-03-29
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多