【问题标题】:Communicate with Rar.exe in Python在 Python 中与 Rar.exe 通信
【发布时间】:2013-02-16 17:59:51
【问题描述】:

我想从 Python 脚本创建一个 RAR 文件。我需要与 Rar.exe 通信,因为我只想要多卷存档集中的第一个 RAR 卷,仅此而已。 -vp 开关确保在每卷之后询问Create next volume ? [Y]es, [N]o, [A]ll。第一次出现这个问题时,我想回答“否”。我该如何做到这一点?

我已经阅读并尝试了很多东西,我发现可以使用pexpect 完成类似的事情。我一直在尝试两个不同的 Windows 端口:wexpectwinpexpect。结果是我的脚本会挂起。没有创建 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')

也欢迎其他方法。

【问题讨论】:

  • 挂在哪一行?
  • @f13o:在上面的代码中,它挂在child = wexpect.spawn(rarexe, args) 上,我们预计它挂在msg = GetMessage(0, 0, 0) 上。 That is this function.

标签: python subprocess interactive rar pexpect


【解决方案1】:

我遇到了同样的问题,因为网络上有几个(错误)版本的 wexpect。

查看my variant,这是一个实例的副本,它对我有用。

这可以安装使用

pip install wexpect

【讨论】:

  • 我看到你被否决了。我只是在提供的脚本上尝试了它,但它对我也不起作用。超时后显示Create next volume ? [Y]es, [N]o, [A]ll error。这是对我过去经验的改进,因为我不记得看到 error 打印。是 wexpect 还是我上面的脚本有问题?我现在用的是 RAR 5.50 x64。
  • 感谢您,而不仅仅是投反对票。你什么时候收到这个消息? (在安装期间?在运行期间(在启动时,在等待提示时)?)您能否将其发布为具有更多详细信息的新问题(github.com/raczben/wexpect/issues)?
  • 消息是问题中程序的输出。在 wexpect 没有检测到的 rar.exe 的问题提示之后,我自己显示error。我在 Windows 上运行它。
  • 您的程序出错可能是wexpect的stderr处理错误,这是一个已知问题。 github.com/raczben/wexpect/issues/2
【解决方案2】:

我的问题的答案分为两部分。

正如 betontalpfa 所说,我必须使用他的version of wexpect。它可以轻松安装:

pip install wexpect

Pexpectexpect_exact 文档解释说它使用纯字符串匹配而不是列表中的编译正则表达式模式。这意味着必须正确转义参数,或者必须使用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!

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多