TypeError:强制转换为Unicode,需要字符串或缓冲区,找到NoneType

Van*_*Gez 5 python function typeerror traceback nonetype

目前为程序编写函数,一个组件是搜索python文件中是否正在使用单个变量.

功能:

def SINGLE_CHAR_VAR(python_filename):
    file = open(python_filename)
    lines = [0]
    SINGLE_CHAR_VAR = []
    for line in file:
        stripped = line.strip('\n\r')
        lines.append(stripped)

    from utils import vars_indents
    variable_list = (vars_indents(python_filename))[0]
    for i in range(1, len(variable_list)):
        if len(variable_list[i][0][0]) == 1:
            SINGLE_CHAR_VAR.append(['SINGLE_CHAR_VAR', i, variable_list[i][0][1], variable_list[i][0][0], lines[i]])      
    return SINGLE_CHAR_VAR?
Run Code Online (Sandbox Code Playgroud)

当我单独使用该功能时 - 该功能正常工作.但是,当我作为一个整体调用该程序时 - 我收到以下错误消息:

Traceback (most recent call last):
  File "<web session>", line 1, in <module>
  File "lint_2.py", line 141, in lint
    sorted_error_list = sorted_list(list_of_file_errors)
  File "lint_2.py", line 84, in sorted_list
    error_list = total_error_list(python_filename)
  File "lint_2.py", line 65, in total_error_list
    single_char_var_list = SINGLE_CHAR_VAR(python_filename)
  File "lint_2.py", line 33, in SINGLE_CHAR_VAR
    file = open(python_filename)
TypeError: coercing to Unicode: need string or buffer, NoneType found
Run Code Online (Sandbox Code Playgroud)

我完全不知道 - 我哪里出错了 - 任何帮助都会非常,非常,非常珍惜!

谢谢.

Mar*_*ers 10

python_filename设置为None,这不是open()函数的有效参数:

>>> open(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, NoneType found
Run Code Online (Sandbox Code Playgroud)

为什么 python_filenameNone不能从您发布的代码来确定.你提供的追溯表明该值来自sorted_list()函数,我建议你开始寻找线索:

  File "lint_2.py", line 84, in sorted_list
    error_list = total_error_list(python_filename)
Run Code Online (Sandbox Code Playgroud)

然而,这只是猜测; 您将必须跟踪该回溯中的所有代码,以查看None首次设置的确切位置.

  • 异常消息告诉您.`open()`期望一个字符串,但是给了一个类型为`NoneType`的对象.只有*one*对象符合该描述:`None`. (2认同)