绕过异常以始终执行命令?

时间:2011-08-11 00:43:10

标签: python

由于收到的帮助here

,以下代码几乎完美无缺
import urllib.request
import zipfile
import subprocess

urls = ["http://url.com/archive1.zip", "http://url.com/archive2.zip", "http://url.com/archive3.zip"]
filename = "C:/test/test.zip"
destinationPath = "C:/test"

for url in urls:
    try:
        urllib.request.urlretrieve(url,filename)
        sourceZip = zipfile.ZipFile(filename, 'r')
        break
    except ValueError:
        pass

for name in sourceZip.namelist():
    sourceZip.extract(name, destinationPath)
sourceZip.close()

subprocess.call(r'C:\WINDOWS\system32\cmd.exe /C "C:\test\test.exe"')

除非当url没有成功下载时,最终的subprocess.call命令永远不会被执行,我收到以下错误:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    for name in sourceZip.namelist():
NameError: name 'sourceZip' is not defined

我一直在玩这个尝试:除了,但不能找到一个有效的解决方案。我相信这是因为try:except命令必须在sourceZip循环中,但由于sourceZip变量永远不会被声明,所以它会失败。我将如何更改此代码以使subprocess.call始终在最后执行,无论下载是否成功? (Python新手)

2 个答案:

答案 0 :(得分:3)

sourceZip = None行之前设置for url in urls。然后在sourceZip is None循环之后测试for以确定您是否能够成功获取文件。例如:

sourceZip = None

for url in urls:
    try:
        urllib.request.urlretrieve(url,filename)
        sourceZip = zipfile.ZipFile(filename, 'r')
        break
    except ValueError:
        pass

if sourceZip is not None:
    for name in sourceZip.namelist():
        sourceZip.extract(name, destinationPath)
    sourceZip.close()

subprocess.call(r'C:\WINDOWS\system32\cmd.exe /C "C:\test\test.exe"')

答案 1 :(得分:0)

将sourceZip初始化为None。然后检查提取和关闭是否都没有。