[英]& was unexpected when unzipping bz2 file
Hello I am trying to write a script to unzip bz2 files with 7zip and python.您好,我正在尝试编写一个脚本来解压缩具有 7zip 和 python 的 bz2 文件。
First when I write首先当我写
PS> & 'C:\Program Files\7-zip\7z.exe' e D:\path\example.bz2
with powershell it is working perfectly.使用 powershell 它运行良好。
So I tried that with Python:所以我用 Python 进行了尝试:
import glob
import subprocess
target = r"D:\path\*.bz2"
tab = glob.glob(target)
for i in range(len(tab)):
subprocess.call("& 'C:\\Program Files\\7-zip\\7z.exe' e %s" %tab[i], shell=True)
And I've got that error message: & was unexpected.而且我收到了错误消息:& 是意外的。 Does someone has an idea why?
有人知道为什么吗?
I am using Python 3.9.2我正在使用 Python 3.9.2
By using shell=True
, you're opting to pass the command line to the platform-native shell, which on Windows is cmd.exe
, not PowerShell , so your PowerShell command line fundamentally cannot be expected to work as-is. By using
shell=True
, you're opting to pass the command line to the platform-native shell, which on Windows is cmd.exe
, not PowerShell , so your PowerShell command line fundamentally cannot be expected to work as-is.
If we take a step back: you don't need to involve the shell at all in your 7z.exe
call , and not doing so also speeds up your operation.如果我们退后一步:您根本不需要在
7z.exe
调用中涉及 shell ,不这样做也会加快您的操作。
By omitting shell=True
, the target executable and its arguments must then be passed as the elements of an array rather than as a single command-line string.通过省略
shell=True
,目标可执行文件及其 arguments 必须作为数组元素而不是单个命令行字符串传递。
for i in range(len(tab)):
exitCode = subprocess.call([ 'C:\\Program Files\\7-zip\\7z.exe', 'e', tab[i] ])
Note the use of exitCode =
, which captures 7z.exe
's exit code and therefore allows you to check for failure.注意
exitCode =
的使用,它捕获7z.exe
的退出代码,因此允许您检查失败。
Alternatively, you could let Python raise an exception on failure automatically , by using subprocess.check_call()
rather than subprocess.call()
或者,您可以让 Python 在失败时自动引发异常,方法是使用 subprocess.check_call
subprocess.check_call()
而不是subprocess.call()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.