Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Run an interactive shell command from Perl script

by zentara (Archbishop)
on Sep 27, 2018 at 18:51 UTC ( #1223175=note: print w/replies, xml ) Need Help??

in reply to Run an interactive shell command from Perl script

Hi, this may help you. The example shows how to run the 'bc' calculator program, and collect its output with IO::Select.
#!/usr/bin/perl use warnings; use strict; use IPC::Open3; use IO::Select; my $pid = open3(\*WRITE, \*READ,\*ERROR,"bc"); my $sel = new IO::Select(); $sel->add(\*READ); $sel->add(\*ERROR); my($error,$answer)=('',''); while(1){ print "Enter command\n"; chomp(my $query = <STDIN>); #send query to bash print WRITE "$query\n"; foreach my $h ($sel->can_read) { my $buf = ''; if ($h eq \*ERROR) { sysread(ERROR,$buf,4096); if($buf){print "ERROR-> $buf\n"} } else { sysread(READ,$buf,4096); if($buf){print "$query = $buf\n"} } } } waitpid($pid, 1); # It is important to waitpid on your child process, # otherwise zombies could be created.
and here is a simple way to start a bash script session, print commands to it, and collect output.
#!/usr/bin/perl use warnings; use strict; use IPC::Open3; $|=1; my $pid=open3(\*IN,\*OUT, \*ERR , '/bin/bash'); # set \*ERR to 0 to send STDERR to STDOUT my $cmd = 'date'; #send cmd to bash print IN "$cmd\n"; my $result = <OUT>; print $result;

I'm not really a human, but I play one on earth. ..... an animated JAPH

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1223175]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2020-07-07 10:24 GMT
Find Nodes?
    Voting Booth?

    No recent polls found