gjoshi has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I have very simple program where I have find out version of Python installed on machine.

#!/usr/local/bin/perl -w use strict; use warnings; open STDERR, '>&STDOUT'; $|=1; print "Hello World \n"; my $tmp = `python -V`; print "Version: $tmp \n"; ~

$tmp is not printing anything, looks like it is blank. output is as follows: Hello World Python 2.6.6 Version: But i am not able to capture the OP. Could anyone please tell me how to get the info?

thanks --girija

Replies are listed 'Best First'.
Re: Python -V command not returning any value
by vinoth.ree (Monsignor) on Sep 28, 2015 at 07:21 UTC

    Try this, it works,

    print "Hello World \n"; my $tmp = `python -V 2>&1`; print "Version: $tmp \n";

    Note that you cannot simply open STDERR to be a dup of STDOUT in your Perl program and avoid calling the shell to do the redirection. This doesn't work:

    open(STDERR, ">&STDOUT"); $alloutput = `cmd args`; # stderr still escapes
    This fails because the open() makes STDERR go to where STDOUT was going at the time of the open(). The backticks then make STDOUT go to a string, but don't change STDERR (which still goes to the old STDOUT).


    All is well. I learn by answering your questions...
Re: Python -V command not returning any value ( Capture::Tiny )
by Anonymous Monk on Sep 28, 2015 at 06:58 UTC

    I have very simple program ... Could anyone please tell me how to get the info? thanks --girija

    Use the convenience that is Capture::Tiny and the Basic debugging checklist

    #!/usr/bin/perl -- use strict; use warnings; use Capture::Tiny qw/ capture /; use Data::Dump qw/ dd /; my @cmd = ( 'python', '-V' ); my( $stdout, $stderr, $exit ) = capture { system { $cmd[0] } @cmd; };; dd({ stdout => $stdout, stderr => $stderr, exit => $exit } ); __END__ { exit => 0, stderr => "Python 2.5\n", stdout => "" }
      Hi all, Also found another way to do this
      open STDOUT, '>', "op.txt" or die "Can't redirect STDOUT: $!"; open STDERR, ">&STDOUT" or die "Can't dup STDOUT: $!";
      thanks --girija

      I came up with a solution using IPC::Open3 before reading your posting with more care. I am new to Capture::Tiny and thank you for the introduction. IPC::Open3 also works but Capture::Tiny can provide something simpler. Your code is interesting pedagogically but the example is as complicated as an open3 solution and maybe a little overkill for the problem.

      use strict; use warnings; use Capture::Tiny 'capture_merged'; my $python_ver = capture_merged { system('python', '-V') }; print "Python version is: $python_ver\n";
      Ron