You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无限循环中函数返回值传递及tradingview函数代码修复

问题分析与解决方案

嘿,我一眼就看到你代码里的两个关键问题啦:

  1. tradingview()里的return放在了while True循环内部,导致函数第一次执行到return就直接终止了,循环根本没法持续运行;
  2. 没法把tradingview()持续生成的两个数值传递给target_balance()。

下面给你两种实用的解决办法,选哪种看你的需求场景:

解决方案1:使用生成器(推荐)

把tradingview()改成生成器函数,用yield替代return,这样函数会在每次产出值后暂停,下次迭代时继续执行循环,完美实现持续输出数值的效果。然后在主逻辑里循环迭代这个生成器,把每次拿到的值传给target_balance()。

修改后的代码示例:

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替代return,持续产出两个值
        yield count_var_short, count_var_long

def target_balance(count_var_short, count_var_long): 
    # 这里补全你的函数逻辑,示例如下:
    current_target = cur_price_VWAP['vwap'] * freeba  # 假设freeba是已定义变量
    print(f"Calculated target balance with shorts={count_var_short}, longs={count_var_long}: {current_target}")

# 主循环:持续从tradingview生成器拿值,传给target_balance
for short_count, long_count in tradingview():
    target_balance(short_count, long_count)
    # 如果需要避免频繁读取文件,可以添加间隔
    # import time
    # time.sleep(1)

解决方案2:在循环内部直接调用目标函数

如果你不想用生成器,也可以直接在tradingview()的循环里调用target_balance(),去掉return语句,让循环一直运行下去:

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) 
        # 直接在这里调用target_balance,传递两个数值
        target_balance(count_var_short, count_var_long)
        # 同样可以添加间隔控制频率
        # import time
        # time.sleep(1)

def target_balance(count_var_short, count_var_long): 
    current_target = cur_price_VWAP['vwap'] * freeba
    print(f"Calculated target balance with shorts={count_var_short}, longs={count_var_long}: {current_target}")

# 启动tradingview的无限循环
tradingview()

两种方案都能解决你的问题:第一种生成器的方式更灵活,后续如果要把数值传给多个函数或做其他扩展处理都很方便;第二种更直接,适合逻辑简单的场景。

内容的提问来源于stack exchange,提问作者abudabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:10