如何打印函数中的变量

2024-03-28 13:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码在下面。正在尝试打印函数中的htmlStr。有什么办法吗

import urllib.request
import re
url = 'http://dummy.restapiexample.com/api/v1/employees'
def testhtml(self):
    response = urllib.request.urlopen(url)
    htmlStr = response.read().decode('ISO-8859-1')
    with open("html.csv","a+") as file:
        file.write(htmlStr)
    pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
    return pdata

print(htmlStr)我做的函数抛出错误

当我做print (htmlStr)得到错误NameError: name 'htmlStr' is not defined

enter image description here


Tags: 代码nameimportrehttpurlresponserequest
1条回答
网友
1楼 · 发布于 2024-03-28 13:30:40

你得到一个错误,因为你试图访问一个域外的局部变量。你知道吗

下面是代码中的内容:

# 1. Begin creating your function
def testhtml(self):
    # 2. This is a local environment. 
    #    Any variables created here will not be accessible outside of the function
    response = urllib.request.urlopen(url)
    # 3. The local variable `htmlStr` is created.
    htmlStr = response.read().decode('ISO-8859-1')
    with open("html.csv","a+") as file:
        # 4. Your local variable `htmlStr` is accessed.
        file.write(htmlStr)
    pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
    return pdata

# 5. Your function is now complete. The local variable `htmlStr` is no longer accessible.

这有道理吗? 如果要打印函数(调试时),可以在函数中放置print语句。(只需确保最终将其删除,以防止混乱的控制台读数。)如果需要访问函数外部的变量,请考虑将其包含在输出中。你知道吗

相关问题 更多 >