I have managed to run external commands from Tk GUI in Perl (Tkx module) without blocking the GUI.
However, I have difficulty to retrieve messages from stderr and stdout: for most commands, nothing is stored in variables $stdout
and $stderr
.
What am I missing in my code?
Thanks
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 ($@);
}
On Linux, I can use
Capture::Tiny
to get the output of an external command:Output:
Edit
To avoid blocking the GUI, develop a small wrapper script instead, for example:
Then use:
Output: