subprocess.CalledProcessError 在 python 中使用 unrar

subprocess.CalledProcessError In python when using unrar

Python 当我尝试使用 winrar(UnRAR.exe) 提取文件时,IDLE 显示错误:

"Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    response=subprocess.check_output(['"C:\Users\B74Z3\Desktop\Test\UnRAR.exe" e -p123 "C:\Users\B74Z3\Desktop\Test\Test.rar"'], shell=True)
  File "C:\Program Files\Python 3.5\lib\subprocess.py", line 629, in check_output
    **kwargs).stdout
  File "C:\Program Files\Python 3.5\lib\subprocess.py", line 711, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['"C:\Users\B74Z3\Desktop\Test\UnRAR.exe" e -p123 "C:\Users\B74Z3\Desktop\Test\Test.rar"']' returned non-zero exit status 1"

代码有什么问题:

import subprocess
response=subprocess.check_output(['"C:\Users\B74Z3\Desktop\Test\UnRAR.exe" e -p123 "C:\Users\B74Z3\Desktop\Test\Test.rar"'], shell=True)

我会对此发表评论,但我没有足够的声誉来这样做。

尝试 运行 在没有 shell 接口的情况下使用命令,即

response=subprocess.check_output(["""C:\Users\B74Z3\Desktop\Test\UnRAR.exe""", "e", "-p123', """C:\Users\B74Z3\Desktop\Test\Test.rar"""])

我还通过使用三重引号从您的命令中消除了添加额外反斜杠的复杂性。这几乎更精确,因为您确切地知道正在使用什么命令和参数 运行.

同样在 windows 上不需要 shell=True 除非你运行宁一个 shell 内置命令,https://docs.python.org/3/library/subprocess.html#popen-constructor

On Windows with shell=True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.