Katherina
Katherina

Reputation: 2223

Run file inside a zipfile?

Is it possible to run a .html or .exe for example, that is inside a zipfile? I'm using the Zipfile module.

Here's my sample code:

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)

After f = z.open(g), I don't know what to do next. I tried using the .read() but it only reads whats inside of the html, what I need is for it to run or execute.

Or is there any othere similar ways to do this?

Upvotes: 2

Views: 2081

Answers (2)

jfs
jfs

Reputation: 414905

Run the first .html file in a zip archive specified at the command line:

#!/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

Example

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

As an alternative to webbrowser you could use os.startfile(os.path.normpath(filename)) on Windows.

Upvotes: 1

Abbas
Abbas

Reputation: 6886

The best approach will be to extract the required file to the Windows temp directory and execute it. I have modified your original code to create a temp file and execute it:

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

Upvotes: 1

Related Questions