python - 如何像 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 笔记本中的本地未知变量中缓存一些重要数据?
理想情况下,我希望代码立即为我提供真实数据,而无需这些[]
.
解决方案
很难说出为什么会发生这种情况,但作为一种可能的解决方法,我会尝试将代码包装在您重新运行的单元格中,在一个重试直到获得非空结果的函数中。
例如,假设除导入之外的所有内容都在重新运行单元格中,这可能是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)
推荐阅读
- makefile - android 使用 arm64-v8a ABI 编译错误“未定义的引用”
- soap - EWS 托管 api 检查用户帐户中是否存在事件
- scala - Guava Cache Generic LoadingCache
- python - 为什么 Tensorflow 网站花卉图像分类需要大约 6 秒才能进行分类?
- php - 我想将时间以 hrs:min:sec 格式存储在数据库中,并以 hrs:min:sec 格式显示时间
- elasticsearch - 大批量索引与涓流请求
- javascript - 查找具有频率值的二维关键字数组出现的更快方法
- excel - Excel,自动填充日期范围,每个日期范围一个单元格
- azure - Azure VM:创建 VHD URI、公共 IP 地址、虚拟网络/子网和 DNS 名称后被删除
- python - 对输入中的数字进行平均的功能,没有限制