在Python中与Rar.exe通信
我想从一个Python脚本里创建一个RAR文件。我需要和Rar.exe进行沟通,因为我只想要一个多卷压缩包中的第一个RAR卷,其他的都不需要。使用-vp
这个选项可以确保在每个卷之后都会问我Create next volume ? [Y]es, [N]o, [A]ll
。第一次出现这个问题时,我想回答“否”。我该怎么做呢?
我查阅了很多资料,发现可以用pexpect来实现这个功能。我尝试了两个不同的Windows版本:wexpect和winpexpect。结果是我的脚本一直卡在那里,没能创建出RAR文件。这是我的代码:
import wexpect
import sys
rarexe = "C:\Program Files\WinRAR\Rar.exe"
args = ['a', '-vp', '-v2000000b', 'only_first.rar', 'a_big_file.ext']
child = wexpect.spawn(rarexe, args)
child.logfile = sys.stdout
index = child.expect(["Create next volume ? [Y]es, [N]o, [A]ll",
wexpect.EOF, wexpect.TIMEOUT], timeout=10)
if index == 0:
child.sendline("N")
else:
print('error')
其他的方法也欢迎分享。
2 个回答
0
我也遇到过同样的问题,因为网上有好几个(有问题的)wexpect版本。
你可以看看我这个版本,这是一个我用过的有效实例的复制品。
你可以通过下面的命令来安装它:
pip install wexpect
0
我问题的答案分为两部分。
正如betontalpfa所提到的,我必须使用他的wexpect版本。这个版本的安装非常简单:
pip install wexpect
expect_exact
的文档在Pexpect上解释说,它使用的是普通的字符串匹配,而不是编译过的正则表达式模式。这意味着参数必须正确转义,或者必须使用expect_exact
方法,而不是expect
。这给了我以下可以工作的代码:
import wexpect
import sys
rarexe = "C:\Program Files\WinRAR\Rar.exe"
args = ['a', '-vp', '-v2000000b', 'only_first.rar', 'a_big_file.ext']
child = wexpect.spawn(rarexe, args)
# child.logfile = sys.stdout
rar_prompts = [
"Create next volume \? \[Y\]es, \[N\]o, \[A\]ll",
"\[Y\]es, \[N\]o, \[A\]ll, n\[E\]ver, \[R\]ename, \[Q\]uit",
wexpect.EOF, wexpect.TIMEOUT]
index = child.expect(rar_prompts, timeout=8)
while index < 2:
# print(child.before)
if index == 0:
print("No next volume")
child.sendline("N")
elif index == 1:
print("Overwriting existing volume")
child.sendline("Y")
index = child.expect(rar_prompts, timeout=8)
else:
print('Index: %d' % index)
if index == 2:
print("Success!")
else:
print("Time out!")
输出结果是:
Overwriting existing volume
No next volume
Index: 2
Success!