简体   繁体   English

如何从Python调用Perl脚本,输入到它?

[英]How to call a Perl script from Python, piping input to it?

I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. 我正在攻击DomainKeys和DKIM对开源电子邮件营销程序的一些支持,该程序使用python脚本通过SMTP发送实际的电子邮件。 I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed. 我决定走快速而肮脏的路线,然后编写一个perl脚本,接受来自STDIN的电子邮件,签名,然后返回签名。

What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. 我想做的是,从python脚本,将字符串中的电子邮件文本传递给perl脚本,并将结果存储在另一个变量中,这样我就可以发送签名的电子邮件。 I'm not exactly a python guru, however, and I can't seem to find a good way to do this. 然而,我并不是一个蟒蛇大师,我似乎无法找到一个很好的方法来做到这一点。 I'm pretty sure I can use something like os.system for this, but piping a variable to the perl script is something that seems to elude me. 我很确定我可以使用像os.system这样的东西,但是将一个变量传递给perl脚本似乎是我无法实现的。

In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python? 简而言之:如何将变量从python脚本传递到perl脚本,并将结果存储在Python中?

EDIT: I forgot to include that the system I'm working with only has python v2.3 编辑:我忘了包括我正在使用的系统只有python v2.3

Use subprocess . 使用子进程 Here is the Python script: 这是Python脚本:

#!/usr/bin/python

import subprocess

var = "world"

pipe = subprocess.Popen(["./x.pl", var], stdout=subprocess.PIPE)

result = pipe.stdout.read()

print result

And here is the Perl script: 这是Perl脚本:

#!/usr/bin/perl

use strict;
use warnings;

my $name = shift;

print "Hello $name!\n";

os.popen()将返回一个带有子进程的stdin和stdout的元组。

from subprocess import Popen, PIPE
p = Popen(['./foo.pl'], stdin=PIPE, stdout=PIPE)
p.stdin.write(the_input)
p.stdin.close()
the_output = p.stdout.read()

"I'm pretty sure I can use something like os.system for this, but piping a variable to the perl script is something that seems to elude me." “我非常确定我可以使用像os.system这样的东西,但是将一个变量传递给perl脚本似乎是我无法实现的。”

Correct. 正确。 The subprocess module is like os.system, but provides the piping features you're looking for. 进程模块类似于os.system,但提供了您正在寻找的管道功能。

I'm sure there's a reason you're going down the route you've chosen, but why not just do the signing in Python? 我确定你选择的路线是有原因的,但为什么不用Python进行签名呢?

How are you signing it? 你好吗? Maybe we could provide some assitance in writing a python implementation? 也许我们可以在编写python实现时提供一些帮助?

I tried also to do that only configure how to make it work as 我也试图这样做只配置如何使其工作

pipe = subprocess.Popen(
            ['someperlfile.perl', 'param(s)'],
            stdin=subprocess.PIPE
        )
response = pipe.communicate()[0]

I wish this will assist u to make it work. 我希望这能帮助你使它发挥作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM