【问题标题】:Running an external command in Perl / Tkx without blocking the GUI (Windows)在 Perl / Tkx 中运行外部命令而不阻塞 GUI (Windows)
【发布时间】:2014-12-30 12:44:24
【问题描述】:

我正在尝试使用 Perl + Tkx 创建一个界面,该界面可以在单击按钮时运行外部命令。

关于如何使用 Tk 模块的文档很多,但很少使用 Tkx。

我仍然找到了一些类似this one 的方法,但我无法使其适用于我的示例。特别是这些帖子包括 Tkx::open、Tkx::configure 和 Tkx::fileevent 的使用......但我还没有弄清楚如何将它们组合在一起。

这是我正在尝试的代码;当点击按钮并按下一个键来终止子进程时,Perl 崩溃并出现错误Free to wrong pool 16389d0 not 328e448 at C:/Perl/lib/Tcl.pm line 433.

注意:我使用的是 ActivePerl 5.12.2。

use Tkx;
use strict;

my $mw = Tkx::widget->new(".");
my $button=$mw->new_ttk__button(-text => "Run", -command => [\&run_cmd, 0]);
$button->g_grid(-column => 0, -row => 0);
my $text = $mw->new_tk__text(-width => 32, -height => 16);
$text->configure(-state => "disabled");
$text->g_grid(-column => 0, -row => 1);
Tkx::MainLoop();

sub run_cmd {
    if (fork()==0) {
        system "pause";
        exit 0;
    }
}

谢谢

【问题讨论】:

    标签: perl tkx


    【解决方案1】:

    在这个问题上花了将近 2 天的时间后,我终于找到了答案,这要归功于 here 的帖子,其中包含我适应 Tkx 的 Tcl 代码。

    解决方案是使用Tkx::open(结合其表亲“读取”和“关闭”)。

    下面的代码可以在不阻塞 GUI 的情况下正确执行命令,但在大多数情况下,我无法检索 STDOUT 和 STDERR(它适用于运行用 java 开发的应用程序,但不适用于 systeminfodiff -v )。

    如果有人对此有所了解,请随时发表评论。

    谢谢

    use Tkx;
    use strict;
    use Data::Dumper;
    
    my ($stdout,$stderr);
    
    my $mw = Tkx::widget->new(".");
    my $button=$mw->new_ttk__button(-text => "Run", -command => [\&run_command, "systeminfo"]);
    $button->g_grid(-column => 0, -row => 0);
    my $text = $mw->new_tk__text(-width => 32, -height => 16);
    $text->insert("end", "Test\n");
    $text->g_grid(-column => 0, -row => 1);
    
    Tkx::MainLoop();
    print "STDOUT: $stdout\n\n","-"x24,"\nSTDERR: $stderr\n";
    
    
    sub run_command {
        my $cmd = shift;
        my $fh = Tkx::open("| $cmd", 'r') or die "$!";
        Tkx::fconfigure($fh, -blocking => 0);
        $stdout.=Tkx::read($fh);
        eval { Tkx::close($fh); };
        $stderr.=$@ if ($@);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多