Python zip.exe 的子进程调用

Python subprocesscall of a zip.exe

我有一个 python 脚本,它使用以下命令压缩了一个文件:

subprocess.call(["zip", "-P", password, "-r", zipName, fileName])

假设我知道密码,以同样的方式解压文件的参数是什么(subprocess.call)?

-x 仅解压部分文件时。

subprocess.call(["unzip","-P",password,zipName,"-x",fileName])

作为旁注,来自 unzip 手册:

-P password

use password to decrypt encrypted zipfile entries (if any). THIS IS INSECURE! Many multi-user operating systems provide ways for any user to see the current command line of any other user; even on stand-alone systems there is always the threat of over-the-shoulder peeking. Storing the plaintext password as part of a command line in an automated script is even worse. Whenever possible, use the non-echoing, interactive prompt to enter passwords. (And where security is truly important, use strong encryption such as Pretty Good Privacy instead of the relatively weak encryption provided by standard zipfile utili- ties.)

你问的是特定于实现的(zip.exe 可以是任何东西),所以我不会给你你可能期望的答案。

相反,我将告诉您如何以更 Pythonic 的方式进行操作。

使用zipfile模块

要制作存档,请执行以下操作:

with zipfile.ZipFile(zipname, 'w') as z:
    z.setpassword(b'asdf')
    z.write(filename)

据此,提取:

with zipfile.ZipFile(zipname) as z:
    z.setpassword(b'asdf')
    z.extractall()

其中 asdf 是您的密码。请注意,您需要 bytes,而不是 str - 假设您使用的是 Python 3。如果您使用 Python 2 , 不要写前导 b.