在perl中运行python脚本

时间:2011-12-28 17:34:30

标签: python perl

我有两个脚本,一个python脚本和一个perl脚本。

如何让perl脚本运行python脚本然后自行运行?

3 个答案:

答案 0 :(得分:8)

这样的事情应该有效:

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);

如果要为子流程提供输入,这也可以类似地工作。

答案 1 :(得分:2)

最好的方法是使用IPC :: Open3在系统级执行python脚本。与使用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代码失败,您可以恢复并继续执行您的程序。

答案 2 :(得分:1)

如果您需要将结果从一个程序传递到另一个程序,那么从shell脚本运行这两个脚本并使用管道(假设您在Unix环境中)可能更简单

相关问题