subprocess.CalledProcessError在python中使用unrar时

时间:2016-04-29 06:40:03

标签: python python-2.7 python-3.x subprocess

当我尝试使用winrar(UnRAR.exe)提取文件时,Python 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)

1 个答案:

答案 0 :(得分:1)

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

尝试运行不带shell接口的命令,即

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

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

同样在Windows上,除非您正在运行内置命令https://docs.python.org/3/library/subprocess.html#popen-constructor的shell,否则不需要shell = True:

  

在具有shell = True的Windows上,COMSPEC环境变量指定默认shell。您需要在Windows上指定shell = True的唯一时间是您希望执行的命令是否内置到shell中(例如dir或copy)。您不需要shell = True来运行批处理文件或基于控制台的可执行文件。