开发者

Bypass exception to always execute command?

The following code works almost perfect, thanks to the help received 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"')

Except that when none of the url's successfully download, the final subprocess.call command never gets executed and I get the following error:

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

I have been playing around a bit with the try: and except, but can not come to a working solution. I believe it is because the try: except command has to be inside the sourceZip loop, but since the sourceZip variable never gets declared, it fails. How would I alter this code to have the subprocess.call always get executed at the end regardless whether the download is successfull or not? (very new to Python)


Set sourceZip = None prior to the for url in urls line. Then test if sourceZip is None after the for loop to determine if you were able to successfully fetch the file. For example:

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"')


Initialize sourceZip to None. Then check if it is not none do the extraction and closing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜