Question

From a Python script I want to create a RAR file. I will need to communicate with Rar.exe because I only want the first RAR volume from a multi-volume archive set, nothing more. The -vp switch makes sure Create next volume ? [Y]es, [N]o, [A]ll is asked after each volume. The first time this question pops up, I want to answer No. How do I accomplish this?

I've been reading and trying a lot of things and I found out something like this can be accomplished with pexpect. I've been trying the two different Windows ports: wexpect and winpexpect. The result is that my script will hang. No RAR file is created. This is my code:

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')

Other approaches are welcome too.

Was it helpful?

Solution 2

The answer to my problem has two parts.

As betontalpfa indicated, I must use his version of wexpect. It can be installed easily:

pip install wexpect

The expect_exact documentation of Pexpect explains that it uses plain string matching instead of compiled regular expressions patterns in the list. This means the parameters must be properly escaped or the expect_exact method must be used instead of expect. It gave me this working code:

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!")

And the output gives:

Overwriting existing volume
No next volume
Index: 2
Success!

OTHER TIPS

I had the same issue, because there are several (buggy) version of wexpect on the web.

Check out of my variant, which is a copy of an instance, which worked for me.

This can be installed using

pip install wexpect

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top