gpt4 book ai didi

脚本中的 Python 变量范围问题

转载 作者:行者123 更新时间:2023-11-28 22:37:49 38 4
gpt4 key购买 nike

我遇到了一些奇怪的事情,一个变量在设置后无法在其他函数中访问。这是一个名为 html.py

的 Celery 任务文件
base_path = ''

@app.task(bind=True)
def status(self):
"""
returns the count of files downloaded and the timestamp of the most recently downloaded file
"""

num_count = 0
latest_timestamp = ''
for root, _, filenames in os.walk(base_path):
for filename in filenames:
file_path = root + '/' + filename
file_timestamp = datetime.fromtimestamp(os.path.getctime(file_path))
if latest_timestamp == '' or file_timestamp > latest_timestamp:
latest_timestamp = file_timestamp
num_count += 1

@app.task(bind = True)
def download(self, url='', cl_id=-1):
if len(url) == 0 or cl_id < 0:
return None

base_path = settings.WGET_PATH + str(cl_id)

log_paths = {
'output' : wget_base_path + '/out.log',
'rejected' : wget_base_path + '/rejected.log'
}

create_files(log_paths)
wget_cmd = 'wget -prc --convert-links --html-extension --wait=3 --random-wait --no-parent ' \
'--directory-prefix={0} -o {1} --rejected-log={2} {3}'.\
format(wget_base_path, log_paths['output'], log_paths['rejected'], url)

subprocess.Popen(wget_cmd, shell = True)

当我通过以下方式调用它时

from ingest.task import html
web_url = 'https://www.gnu.org/software/wget/manual/html_node/index.html'
ingest = html.download.delay(web_url, 54321)

wget 进程按预期启动。但是,文件顶部的 base_path 参数永远不会被设置,所以当我通过

调用 status
status = html.status.delay()

base_path 变量是一个空字符串,尽管 statusdownload 之后被调用。这是因为这些任务是在脚本中而不是在类中吗?

最佳答案

因为在函数download这一行

base_path = settings.WGET_PATH + str(cl_id)

您只需创建一个名称为 base_path 的局部变量。为避免这种情况,您应该在函数中将 base_path 声明为 global。例如:

@app.task(bind = True)
def download(self, url='', cl_id=-1):
if len(url) == 0 or cl_id < 0:
return None

global base_path
base_path = settings.WGET_PATH + str(cl_id)
...

来自 Python docs :

在执行期间的任何时候,至少有三个嵌套作用域的命名空间可以直接访问:

  • 首先搜索的最内层范围包含本地名称
  • 从最近的封闭范围开始搜索的任何封闭函数的范围包含非本地名称,但也包含非全局名称
  • 倒数第二个范围包含当前模块的全局名称
  • 最外层的作用域(最后搜索到的)是包含内置名称的命名空间

如果一个名称被声明为全局的,那么所有的引用和赋值都会直接进入包含模块全局名称的中间作用域。否则,在最内层作用域之外找到的所有变量都是只读的(尝试写入此类变量只会在最内层作用域中创建一个新的局部变量,而同名的外部变量保持不变)。

关于脚本中的 Python 变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179424/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com