UnboundLocalError从.bat运行.py(带API);在命令提示符中运行良好



当我在Windows 10 Python 3.8.2的命令提示符中执行命令时,我得到了预期的行为,我的数据保存为应有的(1.0.3打印用于故障排除):

Microsoft Windows [Version 10.0.19041.746]
(c) 2020 Microsoft Corporation. All rights reserved.
C:Users>SET BEARER_TOKEN=xyz
C:Users>cd C:UsersTwitterConv
C:UsersTwitterConv>python scrape-test.py neonphotography
1.0.3
C:UsersTwitterConv>

然而,当我把它放入。bat文件时,我得到以下错误,当从任何地方运行它:

C:UsersTwitterConv>python scrape-test.py neonphotography
1.0.3
Traceback (most recent call last):
File "scrape-test.py", line 333, in <module>
main()
File "scrape-test.py", line 322, in main
user_ids = get_user_info(headers, filename)
File "scrape-test.py", line 155, in get_user_info
user_df = pandas.json_normalize(json_response["data"])
UnboundLocalError: local variable 'json_response' referenced before assignment

.bat文件:

SET BEARER_TOKEN=xyz
cd /D C:UsersTwitterConv
python scrape-test.py neonphotography

我正试图从同事使用Mac的适应这个项目,我真的希望这很容易,一旦我开始阅读批处理文件。我尝试过使用pyinstaller作为解决方案,但这是一套全新的问题,所以我想我会从这里开始。

为什么我的批处理文件不能正常运行?

查看堆栈跟踪本身是有用的。您的脚本可能失败的唯一方式是对twitter的调用失败。在这种情况下,批处理文件与交互式命令行之间唯一合理的区别是承载令牌不同。因为不记名令牌中经常有百分比符号,所以很可能有什么事情在发生。

我们可以用一个简单的脚本来简化:

# This is example.py
import os
print("BEARER_TOKEN=[" + os.environ.get("BEARER_TOKEN") + "]")

如果你以交互方式运行它,它会像你期望的那样工作:

C:Example>set BEARER_TOKEN=this%is%an%example%token
C:Example>python example.py
BEARER_TOKEN=[this%is%an%example%token]

但是,用一个简单的批处理文件运行它,它不会像预期的那样工作:

@echo off
rem This is example.cmd
set BEARER_TOKEN=this%is%an%example%token
python3 example.py
C:Example>example.cmd
BEARER_TOKEN=[thisantoken]

您需要转义批处理文件中的百分比符号,因为它们的解析方式与交互式提示符不同:

@echo off
rem This is the fixed example.cmd
set BEARER_TOKEN=this%%is%%an%%example%%token
python3 example.py
C:Example>example.cmd
BEARER_TOKEN=[this%is%an%example%token]

最新更新