如何在函数内打印变量

时间:2019-12-25 04:29:59

标签: 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

1 个答案:

答案 0 :(得分:2)

由于尝试访问其域之外的本地变量而收到错误消息。

这是您的代码中的样子:

# 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.

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