在python中导入函数后保存函数返回的值

在python中导入函数后保存函数返回的值,python,function,Python,Function,我从python中的一个文件调用了一个函数(carlabels),希望将该函数返回的值作为输入,以便在代码的后面部分使用。我能够将函数导入到一个新的python文件中,并且能够打印返回的值。如何将这些值保存在文本文件中以进一步使用它们 #detected_cars.py import cartracker #this code is for detecting the cars import cartracker2

我从python中的一个文件调用了一个函数(
carlabels
),希望将该函数返回的值作为输入,以便在代码的后面部分使用。我能够将函数导入到一个新的python文件中,并且能够打印返回的值。如何将这些值保存在文本文件中以进一步使用它们

#detected_cars.py
import cartracker                       #this code is for detecting the cars
import cartracker2                      #slight modification on cartracker    
width = 3296                            #dimention to capture  
height = 2472                           #dimention to capture
gray = cv2.CreateImage(sz, 8, 1)        #create an image of specified dimention
new_fc = 1

def carlabels(carinfo):
    labels=[]
    r=60
    for (tag,xy,orient,err,wl,sq) in carinfo:
        xy2= (int(xy[0]+r*math.sin(math.radians(orient))),int(xy[1]-r*math.cos(math.radians(orient))))
        labels.append((xy,xy2,str(tag)))
    return labels

if new_fc:
    carinfo = cartracker.Analyze_captured_near_gate(gray, area=[width, height], th_factor=0.5, single_edge=0)
else:
    carinfo = cartracker2.Analyze_captured_near_gate(gray, area=[width, height], th_factor=0.5, single_edge=0)

labels = carlabels(carinfo)
当我表演时:

print labels #i can see the id's of the car displayed.
但是,当我尝试导入函数返回的值(如下所示)时,不会显示该值

from detected_cars import carlabels
tag_id_nd_coordinates = labels
print tag_id_nd_coordinates

函数返回一个列表。将其分配给某个对象,然后将其视为任何其他列表

#detected_cars.py
def carlabels():
    return [1, 2, 3]
然后

检测到的\u cars import carlabels的行
不执行您的carlabels函数。它仅使该函数在该文件中可用


如果您想访问在其他脚本中创建的
标签
变量,您应该能够使用
从车辆导入标签
,然后使用
标签
作为列表。

如果您只想在代码中稍后使用该值,则无需将其保存到文件中。只要在需要时调用它(
carlabels()
),或者将它存储为变量并使用它(
labels=carlabels()
),然后(
用(标签)做点什么
)@Holloway如果我想从函数返回的值中访问特定元素,该怎么办?因为当我运行问题中提到的代码时,该值与输出一起打印,我想将该值保存到一个文本文件中,以便以后可以使用它,返回的值是什么?如果您需要
在函数中打印
ed,您可能想更改代码,使其返回。@Holloway显示车辆的标识以及x和y坐标。您可以将
carlabels
函数添加到问题中吗?我以前尝试过这样做。不幸的是,该值没有显示在屏幕上。显示了什么?您可以添加cod吗你试图用这个问题来回答这个问题吗?很抱歉我不明白。@HarikrishnanR,哪一部分?此评论“@HarikrishnanR,编辑以添加替代导入。”
>>> from detected_cars import carlabels # note no .py extension when importing
>>> labels = carlabels()
>>> print(labels)
[1, 2, 3]
>>> print("sum of labels: ", sum(labels))
sum of labels: 6
>>> print('First label: ', labels[0])
First label: 1