How to pass string from python being called from perl?

Assuming the perl code is something like this...

open(STDOUT, ">$PName") || die "Can't redirect stdout";
$status = system("python Example.py $PName.txt");

(That is taken from http://www.linuxquestions.org/questions/programming-9/perl-script-call-python-linux-551063/)

What do I have to do in python to be able to pass a string to the perl script?

Would I need to simply return the string? or print to console? or something else?

Answers


The system command is not useful in Perl for capturing output of a command. You should use backticks to execute a command and write to stdout in the Python script.

#-- returns one string
$result = `command arg1 arg2`;

#-- returns a list of strings
@result = `command arg2 arg2`;

See the linked source below for more information.

Source: executing external commands in Perl


You could just print to console, and in perl use:

my $from_py = `python foo.py bar`;

The simplest way is to use backticks (``) as in

my $output = `python Example.py $PName.txt`;
print "Backticks:\n", $output;

A synonymous approach involves qx//.

my $output = qx/python Example.py $PName.txt/;
print "Backticks:\n", $output;

To read each line, open a pipe from the Python subprocess.

print "Pipe:\n";
open my $fh, "python Example.py $PName.txt |";
while (<$fh>) {
  print "Perl got: ", $_;
}
close $fh or warn "$0: close: $!";

As outlined in the “Safe Pipe Opens” section of the perlipc documentation, you can bypass the shell by splitting the command into arguments.

open my $fh, "-|", "python", "Example.py", "$PName.txt";

Output:

Backticks:
Python program: Example.py
Argument:       pname-value.txt

Pipe:
Perl got: Python program: Example.py
Perl got: Argument:       pname-value.txt

Need Your Help

how to protect from sql injection when using php?id=

php mysql sql sql-injection

Hello I need help finding a way to protect from sql injection on my current project, Im making bash tutorial site but ive run into a problem. I put most my content in database and depending on wha...

Expandable ListView inside 4_level expandable listview

android listview expandablelistview

I would like to know if it is possible to put an Expandable ListView as one child of one element of another Expandable ListView like that i want 4_level of expandable listview.