在Perl中运行Python脚本

3 投票
3 回答
12414 浏览
提问于 2025-04-17 09:09

我有两个脚本,一个是Python脚本,一个是Perl脚本。

我该怎么做才能让Perl脚本先运行Python脚本,然后再运行自己呢?

3 个回答

1

如果你在使用Unix环境,可能更简单的方法是通过一个shell脚本来同时运行这两个脚本。如果你需要把一个程序的结果传递给另一个程序,可以使用管道。

2

最好的方法是通过系统级别来执行python脚本,使用IPC::Open3。这样做比直接用system()更安全,也让你的代码更容易理解。

你可以很简单地使用IPC::Open3来执行系统命令,还能读取和写入这些命令,像这样:

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

这样会创建一个分叉的进程来运行python代码。这意味着如果python代码出错了,你仍然可以恢复并继续你的程序。

9

像这样应该可以工作:

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

如果你需要获取Python脚本的输出:

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

如果你想给子进程提供输入,这个方法也差不多可以用。

撰写回答