Run a python script in perl

11,619

Solution 1

Something like this should work:

system("python", "/my/script.py") == 0 or die "Python script returned error $?";

If you need to capture the output of the Python script:

open(my $py, "|-", "python2 /my/script.py") or die "Cannot run Python script: $!";
while (<$py>) {
  # do something with the input
}
close($py);

This also works similarly if you want to provide input for the subprocess.

Solution 2

The best way is to execute the python script at the system level using IPC::Open3. This will keep things safer and more readable in your code than using system();

You can easily execute system commands, read and write to them with IPC::Open3 like so:

use strict;
use IPC::Open3 ();
use IO::Handle ();  #not required but good for portabilty

my $write_handle = IO::Handle->new();
my $read_handle = IO::Handle->new();
my $pid = IPC::Open3::open3($write_handle, $read_handle, '>&STDERR', $python_binary. ' ' . $python_file_path);
if(!$pid){ function_that_records_errors("Error"); }
#read multi-line data from process:
local $/;
my $read_data = readline($read_handle);
#write to python process
print $write_handle 'Something to write to python process';
waitpid($pid, 0);  #wait for child process to close before continuing

This will create a forked process to run the python code. This means that should the python code fail, you can recover and continue with your program.

Solution 3

It may be simpler to run both scripts from a shell script, and use pipes (assuming that you're in a Unix environment) if you need to pass the results from one program to the other

Share:
11,619
SuperString
Author by

SuperString

Hello World!

Updated on June 24, 2022

Comments

  • SuperString
    SuperString about 2 years

    I have two scripts, a python script and a perl script.

    How can I make the perl script run the python script and then runs itself?