Python popen2 function rewrite (php-mail-parsing)


Python popen2 function rewrite (php-mail-parsing)

我尝试将popen2重写为子进程。波彭。我得到错误。

我的代码:

cmd = '/usr/sbin/sendmail -t -i'
if len(sys.argv) == 3:
  cmd += " -f%s" % sys.argv[2]
# OLD CODE =======================
#(out, s) = popen2(cmd)
#s.write(data)
#s.close()
# ================================
# NEW CODE =======================
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
(out, s) = (p.stdin, p.stdout)
s.write(data)
s.close()
sys.stdout.flush()

在阿帕奇error_log中,我收到错误:

Traceback (most recent call last):
  File "/opt/php-secure-sendmail/secure_sendmail.py", line 80, in <module>
    s.write(data)
IOError: File not open for writing
sendmail: fatal: test@serve.tld(10000): No recipient addresses found in message header
plesk sendmail[2576]: sendmail unsuccessfully finished with exitcode 75

也许有人知道如何弄清楚这段代码?

您可以使用.communicate()方法将data传递给子进程:

cmd = '/usr/sbin/sendmail -t -i'.split()
if len(sys.argv) > 2:
  cmd += ["-f", sys.argv[2]]
p = Popen(cmd, stdin=PIPE, close_fds=True)
p.communicate(data)

请注意,此处不需要shell=True

我已经删除了stdout=PIPE因为我没有看到您的代码中使用的输出。如果要抑制输出;请参阅如何在 Python 2.7 中隐藏子进程的输出。

您正在尝试在仅开放阅读的 stdout 上书写。

stdout 包含新进程的打印输出,您必须写入 stdin 才能向其发送数据。

popen2 返回一个元组(stdout,stdin),这就是注释代码工作的原因。https://docs.python.org/2/library/popen2.html

只需反转元组中的顺序,它就会起作用:

p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
(out, s) = (p.stdout, p.stdin)
s.write(data)
s.close()
sys.stdout.flush()