Python 类型错误:强制转换为 Unicode,需要字符串或缓冲区,找到 NoneType
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26563003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: coercing to Unicode, need string or buffer, NoneType found
提问by Vanessa_Gez
Currently writing a function for a program and one component is to search whether a single variables are being used within a python file.
当前为程序和一个组件编写一个函数是搜索是否在 python 文件中使用了单个变量。
FUNCTION:
功能:
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?
When i used the function by itself - the function works properly. However when i call upon the program as a whole - i get the following error message:
当我单独使用该功能时 - 该功能正常工作。但是,当我整体调用该程序时 - 我收到以下错误消息:
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
I have absolutely no idea - where I am going wrong - any help would be very, very, very cherished!!!
我完全不知道 - 我哪里出错了 - 任何帮助都会非常非常非常珍惜!!!
thanks.
谢谢。
采纳答案by Martijn Pieters
python_filenameis set to None, which is not a valid argument for the open()function:
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
Whypython_filenameis Nonecannot be determined from the code you posted. The traceback you supplied suggests the value originates in the sorted_list()function, I suggest you start looking there for clues:
为什么python_filename是None不能从您发布的代码来确定。您提供的回溯表明该值源自sorted_list()函数,我建议您开始寻找线索:
File "lint_2.py", line 84, in sorted_list
error_list = total_error_list(python_filename)
However, that is just a guess; you'll have to trace through all the code in that traceback to see where exactly the Noneis first set.
然而,这只是一个猜测;您必须跟踪该回溯中的所有代码,以查看None第一次设置的确切位置。
回答by Vikram Sharma
Try writing this way:
尝试这样写:
ssh.exec_command()
stdin.flush()
stdin.channel.shutdown_write()
It should work
它应该工作

