2

例如,是否可以运行 .html 或 .exe,它位于 zipfile 中?我正在使用 Zipfile 模块。

这是我的示例代码:

import zipfile

z = zipfile.ZipFile("c:\\test\\test.zip", "r")
x = ""
g = ""
for filename in z.namelist():
    #print filename
    y = len(filename)
    x = str(filename)[y - 5:]
    if x == ".html":
        g = filename
f = z.open(g)

之后f = z.open(g),我不知道下一步该做什么。我尝试使用,.read()但它只读取 html 内部的内容,我需要的是它运行或执行。

或者有没有其他类似的方法来做到这一点?

4

2 回答 2

1

运行.html命令行指定的 zip 存档中的第一个文件:

#!/usr/bin/env python
import os
import shutil
import sys
import tempfile
import webbrowser
import zipfile
from subprocess import check_call
from threading  import Timer

with zipfile.ZipFile(sys.argv[1], 'r') as z:
    # find the first html file in the archive
    member = next(m for m in z.infolist() if m.filename.endswith('.html'))
    # create temporary directory to extract the file to
    tmpdir = tempfile.mkdtemp()
    # remove tmpdir in 5 minutes
    t = Timer(300, shutil.rmtree, args=[tmpdir], kwargs=dict(ignore_errors=True))
    t.start()
    # extract the file
    z.extract(member, path=tmpdir)
    filename = os.path.join(tmpdir, member.filename)

# run the file
if filename.endswith('.exe'):
    check_call([filename]) # run as a program; wait it to complete
else: # open document using default browser
    webbrowser.open_new_tab(filename) #NOTE: returns immediately

例子

T:\> open-from-zip.py file.zip

作为替代方案,webbrowser您可以os.startfile(os.path.normpath(filename))在 Windows 上使用。

于 2012-01-20T08:23:52.960 回答
1

最好的方法是将所需的文件提取到 Windows 临时目录并执行它。我已经修改了您的原始代码以创建一个临时文件并执行它:

import zipfile
import shutil
import os

z = zipfile.ZipFile("c:\\test\\test.zip", "r")
x = ""
g = ""
basename = ""
for filename in z.namelist():
    print filename
    y = len(filename)
    x = str(filename)[y - 5:]
    if x == ".html":
        basename = os.path.basename(filename) #get the file name and extension from the return path
        g = filename
        print basename
        break #found what was needed, no need to run the loop again
f = z.open(g)

temp = os.path.join(os.environ['temp'], basename) #create temp file name
tempfile = open(temp, "wb")
shutil.copyfileobj(f, tempfile) #copy unzipped file to Windows 'temp' folder
tempfile.close()
f.close()
os.system(temp) #run the file
于 2012-01-20T06:30:12.113 回答