获取Traceback和UnboundLocalError

时间:2018-07-31 18:38:34

标签: python

在我的Python脚本上出现以下错误,该错误应该读取带有股票代码和价格目标的CSV文件。要执行脚本,我需要在CSV传递到脚本中时输入python nameofscript.py nameoftickers.csv

脚本的逻辑非常简单:它以文本文件为参数,并从文件的每一行读取股票代码,触发值和条件(a表示上方,b表示下方)。如果满足此条件,则它将通过Pushover将电子邮件发送到预定的电子邮件地址,并向您的手机(在这种情况下为iPhone)发送推送通知。

jovan@jovan-VirtualBox:~/pythonprojects$ python emailalerts.py symbols.csv 
Opening Google Finance URL...
Checking quotes for AAPL
Traceback (most recent call last):
  File "emailalerts.py", line 74, in <module>
    quote = quote_grab(linelst[0])
  File "emailalerts.py", line 30, in quote_grab
    return price #returns price as a float
UnboundLocalError: local variable 'price' referenced before assignment

下面是python脚本。我对Traceback错误以及局部变量感到困惑。我已经在脚本中定义了“价格”。

import string, re, os, time, smtplib, sys
from urllib import urlopen
import httplib, urllib #used in the Pushover code


def quote_grab(symbol):

    baseurl = 'http://google.com/finance?q='
    urlData = urlopen(baseurl + symbol)

    print 'Opening Google Finance URL...'

    # Another option: namestr = re.compile('.*name:\"' + symbol + '\",cp:(.*),p:(.*?),cid(.*)}.*')
    namestr = re.compile('.*name:\"' + symbol + '\",cp:(.*),p:(.*?),cid(.*)') # "?" used as there is a second string "cid" in the page and the Match was being done up to that one. The "?" keeps it to the 1st occurrence.

    print 'Checking quotes for ' + symbol

    for line in urlData:

        m = re.match(namestr, line)

        if m:
            #Since the method m.group(2) returns a string in the form "xxxx", it cannot be converted to float,
            #therefore I strip the "" from that string and pass it to the float function.
            priceStr = m.group(2).strip('"')
            price = float(priceStr)


    urlData.close()
    return price #returns price as a float

def pushover(msg):

    conn = httplib.HTTPSConnection("api.pushover.net:443")
    conn.request("POST", "/1/messages.json",
        urllib.urlencode({
            "token": "________",
            "user": "________",
            "message": msg,
    }), { "Content-type": "application/x-www-form-urlencoded" })
    conn.getresponse()


def send_email(sbjt, msg):
    fromaddr = '________'
    toaddrs = '________'
    bodytext = 'From: %s\nTo: %s\nSubject: %s\n\n%s' %(fromaddr, toaddrs, sbjt, msg)

    # Credentials (if needed)
    username = '________'
    password = '________' 

    # The actual mail sent
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, bodytext)
    server.quit()

#------------------------
# Constants
file = sys.argv[1]

#------------------------

# Opens .cvs file, gets string at last line, converts it to list so that the comparison in the
# IF statement below can be done
csvFile = open(file, 'r')
body = 'Changes:\n'
chg = False

for line in csvFile:
    linelst = line.split(',')
    quote = quote_grab(linelst[0])

    if quote>float(linelst[1]) and linelst[2]==('a\n' or 'a'):
        body = body + 'Price for %s went up to %s (threshold = %s)\n' % (linelst[0], quote, linelst[1])
        chg = True
    if quote<float(linelst[1]) and linelst[2]==('b\n' or 'b'):
        body = body + 'Price for %s went down to %s (threshold = %s)\n' % (linelst[0], quote, linelst[1])
        chg = True

if chg:
    print 'sending email...'
    send_email('Stock Price Changes',body)
    print 'sending message to pushover...'
    pushover(body)

csvFile.close()

1 个答案:

答案 0 :(得分:1)

您正在从函数price返回quote_grab,如果urlData为空,则for的迭代不会发生,或者当{{1} }不包含任何正则表达式m。这就是match的原因。

您可以为UnboundLocalError定义一个默认值,以返回上述情况:

price