如何让代码在 python 中的进程之间保存局部变量,就像 ipython notebook 那样?

How do I make code save local variables between its processes in python like ipython notebook does?

我觉得我的标题不清楚,所以...我制作了这段代码,它以这些 match_ids 的数组形式获取顶级 Dota 电视游戏,并在最后打印它们。 STEAM_LGNSTEAM_PSW是steamlogin/password的组合。

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 笔记本时 -> 当我第一次 运行 电池时 -> 它 returns 我

[]

但是当我第二次做的时候,它returns我是一个真实的数据,例如

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

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

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

的文件中
import subprocess
import time 

### some code ###

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

并且当 运行ning 项目代码总是打印 [] 就像它在 Anaconda ipython notebook 中第一个 Shift+Enter cell-running 所做的那样。

[]
[] 
[]
...

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

理想情况下,我希望代码在没有这些的情况下立即给我真实数据 []

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

例如,假设除了导入之外的所有内容都在重新运行的单元格中,这可能是 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)