在zip文件中运行文件?

2 投票
2 回答
1975 浏览
提问于 2025-04-17 10:35

有没有办法运行一个在压缩文件(zip文件)里的 .html 或 .exe 文件呢?我正在使用 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 文件里的内容,我需要的是让它运行或者执行。

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

2 个回答

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
1

在命令行中运行一个压缩包里的第一个 .html 文件:

#!/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,在Windows上你还可以使用 os.startfile(os.path.normpath(filename)) 来打开文件。

撰写回答