【问题标题】:TypeError: coercing to Unicode, need string or buffer, NoneType foundTypeError:强制转换为 Unicode,需要字符串或缓冲区,找到 NoneType
【发布时间】:2014-12-21 04:22:03
【问题描述】:

目前为一个程序和一个组件编写一个函数是搜索一个变量是否在一个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​

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

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

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

谢谢。

【问题讨论】:

标签: python function typeerror traceback nonetype


【解决方案1】:

试试这样写:

ssh.exec_command()
stdin.flush()
stdin.channel.shutdown_write()

它应该可以工作

【讨论】:

    【解决方案2】:

    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
    

    为什么 python_filenameNone 无法从您发布的代码中确定。您提供的回溯表明该值源自sorted_list() 函数,我建议您开始从那里寻找线索:

      File "lint_2.py", line 84, in sorted_list
        error_list = total_error_list(python_filename)
    

    不过,这只是猜测;您必须跟踪该回溯中的所有代码,以查看第一次设置 None 的确切位置。

    【讨论】:

    • 你怎么知道python_filename设置为none??
    • 异常信息告诉你。 open() 需要一个字符串,但是却得到了一个 NoneType 类型的对象。只有 一个 对象符合该描述:None
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2019-04-02
    • 1970-01-01
    • 2021-03-28
    • 2015-02-01
    • 1970-01-01
    相关资源
    最近更新 更多