2

たとえば、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内の内容しか読み取れません。必要なのは、実行または実行することです。

または、これを行う他の同様の方法はありますか?

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

代わりに、Windowsでwebbrowser使用できos.startfile(os.path.normpath(filename))ます。

于 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 に答える