Search code examples
pythonperlsubprocessgetopt-long

Call GetOptions in perl script from Python subprocess


I have python application running on ubuntu server 16.04 with lines like this:

var1 = "--var1 " + var1
var2 = "--var2 " + var2
proc = subprocess.Popen(["sudo", "perl", "/path/script.pl", str(var1), str(var2) ], stdout=subprocess.PIPE)

Perl script contains following lines:

#!/usr/bin/perl
use File::Path;
use Getopt::Long;
use strict;
use warnings;

my $var1 = '';
my $var2 = '';

print "Started ";

GetOptions ("var1=s" => \$var1, "var2=s" => \$var2) or die ("Error");

print "Vars: FIRST = $var1 SECOND = $var2 ";
...

This application is run by member of sudo group who has permission to run any sudo commands without password. When i run this command from terminal as that user:

su that_user
sudo perl /path/script.pl --var1 XXX --var2 YYY

Im getting desired output:

Started 
Vars: FIRST = XXX SECOND = YYY

But when i run it as subprocess from python i only get:

Started 

If i remove

or die ("Error")

part, i will get:

Started 
Vars: FIRST =  SECOND = 

And no error or anything. As I pretty new to perl i suspect there is a syntax error in the way i call GetOptions, but reading docs and googling for quite some time didn't get me anywhere.


Solution

  • The GetOptions(...) line in the Perl script specifies how the input is submitted to the script:

    script.pl --var1 s1 --var2 s2
    

    You use it correctly from the command line.

    However, your Python script passes the values in variables var1 and var2 as a single string each. You need to spell out the whole command line

    proc = subprocess.Popen(["sudo", \
        "perl", "/path/script.pl", "--var1", str(var1), "--var2", str(var2) ], \
        stdout=subprocess.PIPE)
    

    Here var1 contains only the value, not the "--var1 " string as in the question (same for var2).