[英]Python: returning 'None' from a sub and printing return value
I have the python script below which returns a variable which can either be None
or a blob of data read from a file. 我在下面的python脚本返回一个变量,该变量可以是
None
或从文件读取的blob数据。 I thought this would be an easy way to determine one of three states: 我认为这将是一种确定三种状态之一的简单方法:
None
None
This (also below) is the error I am getting. 这(也在下面)是我得到的错误。 I could just assign
""
to data
instead of None
and test for an empty variable but that seems a little cheesy. 我可以只为
data
而不是None
分配""
并测试一个空变量,但这看起来有点俗气。 Printing the variable wrapped in str()
might work but that seems like a lot of extra typing (or special function to print the variable) every time I want to print the variable. 打印包含在
str()
的变量可能会起作用,但每次我想打印变量时,这似乎都需要额外的输入(或打印变量的特殊功能)。 I must be waaayyy off base here. 我必须在这里离开基地。
$ ./foo.py
Traceback (most recent call last):
File "./foo.py", line 20, in <module>
print " data read was " + line_read
TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects
code: 码:
#!/usr/bin/python
import sys, os
def get_data (src):
data = None
if os.path.isfile (src):
with open(src, 'rt') as f:
data = f.read
return data
line_read = get_data('foo.txt')
if line_read is None:
print "no data in file"
sys.exit(1)
print " data read was " + line_read
It seems the problem is you are using f.read
. 看来问题是你正在使用
f.read
。 Python supports high-order programming, which in essence allows you to assign functions/method to variables. Python支持高阶编程,实质上允许您将函数/方法分配给变量。 Then, what you are returning from
get_data
is basically a function which cannot be concatenated with a string which is the error you are getting, so to fix this call the method read
as follows: 那么,你是从返回
get_data
基本上是不能用一个字符串,它是你所得到的错误串接功能,所以要解决这个问题调用方法read
如下:
#!/usr/bin/python
import sys, os
def get_data (src):
data = None
if os.path.isfile (src):
with open(src, 'rt') as f:
data = f.read() # this will solve your problem
return data
line_read = get_data('foo.txt')
if line_read is None:
print "no data in file"
sys.exit(1)
print " data read was " + line_read
您刚刚将变量data
分配给具有该data = f.read
调用的方法,您应该实际调用该方法:
data = f.read()
You should perhaps add parenthesis from wherever you are calling a function. 您应该从调用函数的任何位置添加括号。 In your program,
f.read()
is a function but you typed it as f.read
which causes the error. 在您的程序中,
f.read()
是一个函数,但您将其键入为f.read
会导致错误。 The solution is to replace f.read
with f.read()
. 解决方案是用
f.read()
替换 f.read
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.