Popen stdout=Pipe输出的python问题

Popen stdout=Pipe输出的python问题,python,python-2.7,openssl,pipe,popen,Python,Python 2.7,Openssl,Pipe,Popen,我是python新手,如果我遗漏了一些“显而易见”的东西,请原谅 目前,我正在编写一个脚本,为DNSSEC生成TLSA记录 #!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE def makeTLSA(): der_cert_proc = Popen(['openssl', 'x509','-in','/etc/letsencrypt/live/example.com/cer

我是python新手,如果我遗漏了一些“显而易见”的东西,请原谅

目前,我正在编写一个脚本,为DNSSEC生成TLSA记录

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE


def makeTLSA():
    der_cert_proc = Popen(['openssl', 'x509','-in','/etc/letsencrypt/live/example.com/cert.pem','-outform','DER'], stdout=PIPE, stderr=PIPE)
    der_cert_output = der_cert_proc.communicate()[0].strip()

    return der_cert_output

print makeTLSA()
目前仅以DER格式打印证书。但输出与调用不同

opensslx509-in/etc/letsencrypt/live/example.com/cert.pem-outform DER

但是如果我把它改成

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE


def makeTLSA():
    der_cert_proc = Popen(['openssl', 'x509','-in','/etc/letsencrypt/live/example.com/cert.pem'], stdout=PIPE, stderr=PIPE)
    der_cert_output = der_cert_proc.communicate()[0].strip()

    return der_cert_output

print makeTLSA()
它的输出与

opensslx509-in/etc/letsencrypt/live/example.com/cert.pem

Python在Centos 7机器上是2.7.5版本。

根据

communicate()

您可以使用这两种方法来检查这一点

der_cert_output = (der_cert_proc.communicate()[0].strip() + 
                   der_cert_proc.communicate()[1].strip())
或者在命令行中删除stderr:
openssl。。。。2> /dev/null

不清楚您的问题是什么。您想要哪种输出,特别是它与您得到的有什么不同?请通过编辑问题来回答。无关:不要设置
stderr=PIPE
,除非您想捕获它。检查退出代码(
deru cert\u proc
)和错误输出(来自
.communicate()
)的第二个结果)。它现在可以工作了。只需更改此项:
返回der\u cert\u output+'\r'
现在结果与在Bash中调用openssl命令相同,因此您必须添加
\r
?但是您刚刚调用了字符串上的strip(它删除了空格,例如
\r
)。也许只是不调用字符串上的strip?注意:多次调用
.communicate()
是没有意义的--
.communicate()
等待进程退出。要同时获取stdout和stderr,请设置
stdout=PIPE,stderr=PIPE
并存储返回值:
stdout\u输出,stderr\u输出=der\u证书进程通信()