2017-10-08 56 views
-2

我得到一个错误,当我尝试运行这个简单的Python脚本:NameError:名字 'urlstring' 没有定义

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

+0

错误显然告诉你现在有'urlstring',所以也许你的代码失败了,而不是'try',你的'except'已经跑了?为什么不把m = re.findall()移到'try/except'的东西? – senaps

+0

感谢它的作品 –

+0

不要抓住所有的例外!这不是口袋妖怪! –

回答

0

不知道如果这是一个错字,但是当您为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 (..) 

你也应该捕捉异常时,捕获所有的人是不是一个好主意,更具体。

+0

如果你downvote,至少发表评论 – Vinny

0

使用对方的回答来修复代码:

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) 

这是一个很好的做法,做的事,并请求原谅,所以做任何你想做的事情,然后如果有赶上错误。 EAFP

相关问题