我正在编写一个脚本,在我的脚本中我有这个功能:
def insert_image(cursor, object_id, sku):
product_obj = core.Object.get(object_id)
string_sku = str(sku)
folder = string_sku[0] + string_sku[1] + string_sku[2]
found_url = False
# KLUDGE This is ugly and redundant, however putting this in an if elif elif else throws error when url not found
# try this url first
try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)):
urllib.URLopener().retrieve("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku), "%sPR-IT,PM.jpg" % (sku))
found_url = True
except:
found_url = False
# If that one didn't work try this one
if found_url == False:
try urllib.urlopen("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku)):
urllib.URLopener().retrieve("http://<path to images>/%s/%sPK-PT,PM.jpg" % (folder, sku), "%sPK-PT,PM.jpg" % (sku))
found_url = True
except:
found_url = False
# If still nothing, one last attempt
if found_url == False:
try urllib.urlopen("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku)):
urllib.URLopener().retrieve("http://<path to images>/%s/%sCC-PT,IM.jpg" % (folder, sku), "%sCC-PT,IM.jpg" % (sku))
found_url = True
except:
found_url = False
# We failed to find an image for this product, it will have to be done manually
if found_url == False:
log.info("Could not find the image on notions")
return False
# Hey we found something! Open the image....
send_image = open('%sPK-PT,PM.jpg' % sku, 'r')
# ...and send it for processing
if product_obj.set_image(send_image, 5, 1) == False:
return False
else:
log.debug("Inserted Image")
return True
这工作正常,直到我添加了尝试捕获。我确实有 if, elif,函数运行得很好。这是我的电话和在它之前运行的代码片段:
if rollback == False:
# Nah -- it's all good SAVE IT!
count += 1
log.debug("INSERT %s" % count)
conn.commit()
else:
# Yeah something went wrong, errors reported why, roll it back
conn.rollback()
log.debug("skipped %s" % skip_count)
# Insert images
if rollback == False:
sku = row[0]
if insert_image(cursor, object_id, sku) == False:
log.error("Could not get the image inserted for product: %s" % object_id)
conn.rollback()
else:
conn.commit()
我的错误是:
16:33:46,153 DEBUG [pylons-admin] Inserted Description
16:33:46,164 DEBUG [pylons-admin] Inserted Attributes
16:33:46,164 DEBUG [pylons-admin] INSERT 1
Traceback (most recent call last):
File "<console>", line 47, in <module>
NameError: name 'insert_image' is not defined
我不知道第 47 行是什么意思,因为调用在第 2101 行,再次在我添加尝试之前,它发现函数很好。当我添加尝试时,我还将第一次提交切换到 insert_image 调用之前,就像你现在看到的那样,在提交之前是在我们调用 insert_image 之后。我检查了缩进、空格和制表符,但无济于事。
我使用 TextMate,当我从 TextMate 运行脚本时,这里出现语法错误:
try urllib.urlopen("http://<path to images>/%s/%sPR-IT,PM.jpg" % (folder, sku)):
它指向 ( on (文件夹...但我看不出哪里有语法错误。请帮忙。我已经在这个脚本上工作了几个星期了,这应该是最后一次运行测试并称之为完成:(