首页 > 解决方案 > 如何像 ipython notebook 一样让代码在 python 中的进程之间保存局部变量?

问题描述

我认为我的标题不清楚,所以...我制作了这段代码,它将顶级 Dota TV 游戏作为这些 match_id 的数组并在最后打印出来。STEAM_LGN,STEAM_PSW是 Steam 登录名/密码组合。

from steam.client import SteamClient
from dota2.client import Dota2Client

client = SteamClient()
dota = Dota2Client(client)

@client.on('logged_on')
def start_dota():
    dota.launch()

match_ids = []
@dota.on('top_source_tv_games')
def response(result):
    for match in result.game_list: # games
        match_ids.append(match.match_id)  
    
def request_matches():
    dota.request_top_source_tv_games()

client.cli_login(username=STEAM_LGN, password=STEAM_PSW)

request_matches()
dota.on('top_source_tv_games', response)
print(match_ids)

我有问题的事情

使用 Anaconda iPython Notebook 时 -> 当我第一次运行单元时 -> 它返回给我

[]

但是当我第二次这样做时,它会返回一个真实的数据,例如

[5769568657, 5769554974, 5769555609, 5769572298, 5769543230, 5769561446, 5769562113, 5769552763, 5769550735, 5769563870]

所以每次我在我的 ipython notebook 沙盒中玩时 -> 我点击Shift+Enter两次并获取数据。

但现在我需要将此代码转移到更大的项目中。因此,例如,假设我将该代码保存到dota2.info.py文件中,并在另一个文件中引用该代码dota2.info.py

import subprocess
import time 

### some code ###

while(True):
    subprocess.call(['python', './dota2info.py'])
    time.sleep(10)

并且在运行项目代码时,它总是[]Shift+Enter在 Anaconda ipython 笔记本中第一次运行单元时那样打印。

[]
[] 
[]
...

所以我的问题是在这种情况下我应该怎么做?如何解决这个问题(我不知道)ValvePython/dota2 代码在 ipython 笔记本中的本地未知变量中缓存一些重要数据?

理想情况下,我希望代码立即为我提供真实数据,而无需这些[].

标签: pythonjupyter-notebookpycharmsteam

解决方案


很难说出为什么会发生这种情况,但作为一种可能的解决方法,我会尝试将代码包装在您重新运行的单元格中,在一个重试直到获得非空结果的函数中。

例如,假设除导入之外的所有内容都在重新运行单元格中,这可能是dota2info.py

from steam.client import SteamClient
from dota2.client import Dota2Client
import time

def get_results():
    client = SteamClient()
    dota = Dota2Client(client)

    @client.on('logged_on')
    def start_dota():
        dota.launch()

    match_ids = []
    @dota.on('top_source_tv_games')
    def response(result):
        for match in result.game_list: # games
            match_ids.append(match.match_id)  
        
    def request_matches():
        dota.request_top_source_tv_games()

    client.cli_login(username=STEAM_LGN, password=STEAM_PSW)

    request_matches()
    dota.on('top_source_tv_games', response)
    return match_ids

if __name__ == "__main__":
    results = get_results()
    max_retries = 10
    retries = 0
    while not results and retries < max_retries:
        time.sleep(3)  # wait number of seconds to retry
        results = get_results()
        retries += 1

    print(results)

推荐阅读