捕获Python中sendpraat命令产生的Praat错误消息

2024-09-20 22:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

您可以启动Praat的一个实例,然后使用sendpraat.exe向其发送GUI命令。因此,如果您在后台运行Praat,下面的命令将使它作为声音对象读入本地mysound.wav文件:

sendpraat praat "Read from file... mysound.wav"

有很多方法可以通过Python发送这个命令,例如:

^{pr2}$

但是如果mysound.wav不存在,Praat实例将弹出一个包含错误的消息框。如何在Python中捕获此错误消息的内容并避免弹出窗口?在

这些解决方案不能解决问题:

  1. 对于这个特定的例子,如果文件存在,我可以签入Python。但我还需要处理Praat可能抛出的所有其他错误,比如编码有问题时,或者样本被剪裁时。

  2. 我可以在命令(sendpraat praat nocheck "Read from file... mysound.wav")之前使用nocheck来避免弹出,但是Python无法知道命令失败了。


Tags: 文件实例from命令消息read错误exe
1条回答
网友
1楼 · 发布于 2024-09-20 22:54:16

nocheck是Praat中进行错误处理的唯一方法,尽管它可能是有限的。如果您想从Python(或任何其他类似的)以编程方式使用GUI,那么进行错误处理的最佳方法是使用nocheck,然后通过查找这些命令的副作用来捕获错误。在

如果您正在打开一个Sound,那么您可以做assert numberOfSelected("Sound")或类似的操作(使用或多或少优雅的测试)。如果要将某些内容写入磁盘,可以使用fileReadable()查看文件是否已创建。在

或者,如果您实际上没有使用GUI,您可以完全绕过sendpraat,并通过控制台使用Praat(对于6.0之前的版本,Windows需要一个名为praatcon的不同二进制文件,但较新的版本使用带有 run选项的相同程序)。在

您不能直接向它传递命令,但可以将这些命令封装到脚本中,然后执行subprocess.call('praat run path/to/my/script.praat arguments')或类似的操作。然后,您就可以使用Python捕捉该脚本中的错误(=您的命令),或者实现与上述相同的手动错误检查。在

更新:示例

下面是一个示例(在Perl和Linux中,但是您已经明白了):

#!/usr/bin/env perl

use Capture::Tiny ':all';
use Try::Tiny;

try {
  ($stdout, $stderr, $exit) = capture {
    system( 'praat', ' run', '~/stdout.praat' );
  }
}
catch {
  chomp;
  warn "It died: $_";
};

print "STDOUT:\n$stdout\n";
print "STDERR:\n$stderr";

以及stdout.praat的内容:

^{pr2}$

输出:

user@linux:~$ perl stdout.pl
STDOUT:
abcde

STDERR:
Error: No Sound selected.
Formula not run.
Script line 4 not performed or completed:
« assert selected("Sound") ; Fail »
Script “/home/user/stdout.praat” not completed.
Praat: command file “/home/user/stdout.praat” not completed.

更新:try/catch in Praat

自从我写下这个答案以来,我已经成功地实现了a try/catch procedure for Praat的一个非常基本的版本。有了它,一个像

include path/to/try.proc

writeInfoLine: "Before fail"

call try
  ... abc$ = "abcde"                                \n
  ... num$ = "0123456789"                           \n
  ... Create Sound as pure tone: "tone",            \n
  ...   ... 1, 0, 0.4, 44100, 440, 0.2, 0.01, 0.01  \n
  ... assert selected("TextGrid")  ; Fail           \n
  ... Remove                       ; Won't run      \n

if try.catch
  appendInfoLine: "Failed!"
endif

将在不崩溃的情况下执行,留下由于删除它的行没有运行而创建的声音。在

该过程在通过CPrAN分发的utils插件中可用,并且实现了here。在

相关问题 更多 >

    热门问题