名称错误:未定义名称“urlstring”

2024-10-06 07:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图运行这个简单的python脚本时,出现了一个错误:

    for url in urllist:
            try:
                file = urllib2.urlopen (url)
                urlstring = file.read ()
            except:
                print "Can't open URL"
                pass
            m = [ ]
            m = re.findall (


r'file:///\\results.cal.ci.spirentcom.com\\smt\\SCMSmartTest\\\d+.\d+\\BLL\d+_IL\d+\\.*?\\TC\S+tcl',
            urlstring)
        copyFileCounts = 1

显示以下错误:

Traceback (most recent call last): File "D:\Python\untitled\regression.py", line 75, in urlstring) NameError: name 'urlstring' is not defined


Tags: in脚本urlforread错误urllib2can
2条回答

不确定是不是打字错误,但是当你给urlstringfile赋值时,会有一个空格。在

当使用try .. catch时,您应该将try块中的代码保持尽可能小:如果出现问题,您将知道原因,而无需进行大量调试。在

您可以使用else子句。在

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

所以你的代码应该是这样的:

for url in urllist:
    try:
        file = urllib2.urlopen(url)
        urlstring = file.read()
    except IOError as e:
        print "Can't open URL: {}".format(e.message)
    else:
        m = []
        m = re.findall (..)

在捕捉异常时还应该更具体,捕捉所有异常并不是一个好主意。在

使用另一个答案来修复代码:

m = []
for url in urllist:
        try:
            file = urllib2.urlopen (url)
            urlstring = file.read ()
            m = re.findall (r'file:///\\results.cal.ci.spirentcom.com\\smt\\SCMSmartTest\\\d+.\d+\\BLL\d+_IL\d+\\.*?\\TC\S+tcl',
        urlstring)
            copyFileCounts = 1
        except IOError as e:
            print "Can't open URL: {}".format(e.message)

做这件事并请求原谅是一个很好的做法,所以做任何你想做的事,然后抓住错误

相关问题 更多 >