我已经设法在 Perl(Tkx 模块)中从 Tk GUI 运行外部命令,而不会阻塞 GUI。
但是,我很难从 stderr 和 stdout 检索消息:对于大多数命令,没有任何内容存储在变量$stdout
和$stderr
.
我的代码中缺少什么?
谢谢
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 ($@);
}