【问题标题】:call perl script from python works in commands.getstatusoutput but not in subprocess.call从 python 调用 perl 脚本在 commands.getstatusoutput 中有效,但在 subprocess.call 中无效
【发布时间】:2012-09-11 20:21:15
【问题描述】:

我有一个 python 脚本,它必须调用 perl 脚本才能从远程服务器获取数据。 perl 脚本必须保留 perl,它是第三方,我在那里没有任何选择。 我正在尝试删除以前的开发人员在代码周围卡住的所有过时和弃用的东西,所以我想用子进程调用替换 commands.getstatusoutput 调用,但不知何故我似乎无法得到它工作...

到目前为止,脚本是通过 commands.getstatusoutput(string) 调用的,其中 string 是对 perl 脚本的完整系统调用,如 '/usr/bin/perl /path/to/my/perl/script. pl

我创建了一个参数列表(args = ['/usr/bin/perl', '/path/to/my/perl/script.pl', '

args = ['/usr/bin/perl', '/path/to/my/perl/script.pl', '<', '/path/to/my/input']
strOut = subprocess.call(args)
print strOut

不幸的是,这失败并出现错误:

port absent at /path/to/my/perl/script.pl line 9.

perl 脚本是:

#!/usr/bin/perl
use IO::Handle;
use strict;
use Socket;
my ($remote, $port, $iaddr, $paddr, $proto, $ligne);
$remote = shift || 'my.provider.com';
$port   = shift || 9000;
if ($port =~ /\D/) { $port = getservbyname ($port, 'tcp'); }
die "port absent" unless $port;

尽管在这里(Call perl script from pythonHow to call a perl script from python?How can I get the results of a Perl script in Python script?Python getstatusoutput replacement not returning full output 等)和其他地方阅读了其他类似的主题,但我感觉我遗漏了一些明显的东西,但我不知道是什么。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: python perl command subprocess popen


    【解决方案1】:

    重定向&lt; 是一个shell 功能。如果你想使用它,你需要将一个字符串传递给subprocess.call 并使用shell = True。例如:

    args = ['/usr/bin/perl', '/path/to/my/perl/script.pl', '<', '/path/to/my/input']
    strOut = subprocess.call(' '.join(args), shell = True)
    

    或者,您可以这样做:

    args = ['/usr/bin/perl', '/path/to/my/perl/script.pl']
    with open('path/to/my/input') as input_file:
        strOut = subprocess.call(args, stdin = input_file) 
    

    最后,strOut 将保存您的 perl 程序的返回码——这似乎是一个有趣的名字。如果你想从你的 perl 程序中获取输出流(stdout),你可能需要将subprocess.Popenstdout=subprocess.PIPEcommunicate 结合使用。

    【讨论】:

    • 我最衷心地感谢您的详细回答,它真的帮助了我。这正是我所缺少的。是的,我需要 subprocess.PIPE 并进行通信以获取我想要的数据,正如您非常正确地指出的那样。
    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多