4

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?

3 Answers 3

3

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

my $from_py = `python foo.py bar`;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.