Python:通过读取stdou关闭for循环

2024-10-01 07:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

import os

dictionaryfile = "/root/john.txt"
pgpencryptedfile = "helloworld.txt.gpg"

array = open(dictionaryfile).readlines()


for x in array:
    x = x.rstrip('\n')
    newstring = "echo " + x + " | gpg --passphrase-fd 0 " + pgpencryptedfile
    os.popen(newstring)

我需要在for循环中创建一些东西来读取gpg的输出。当gpg输出这个字符串gpg: WARNING: message was not integrity protected时,我需要关闭循环并打印成功!

我怎么能做到这一点?背后的原因是什么?

谢谢大家!


Tags: inimporttxtforosrootopenjohn
3条回答
import subprocess


def check_file(dictfile, pgpfile):
    # Command to run, constructed as a list to prevent shell-escaping accidents
    cmd = ["gpg", " passphrase-fd", "0", pgpfile]

    # Launch process, with stdin/stdout wired up to `p.stdout` and `p.stdin`
    p = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE)

    # Read dictfile, and send contents to stdin
    passphrase = open(dictfile).read()
    p.stdin.write(passphrase)

    # Read stdout and check for message
    stdout, stderr = p.communicate()
    for line in stdout.splitlines():
        if line.strip() == "gpg: WARNING: message was not integrity protected":
            # Relevant line was found
            return True

    # Line not found
    return False

然后使用:

^{pr2}$

如果“gpg:WARNING:”消息实际上在stderr上(我怀疑是这样),请将subprocess.Popen行改为:

p = subprocess.Popen(cmd, stdin = subprocess.PIPE, stderr = subprocess.PIPE)

..以及从stdout到{}的for循环,如下所示:

for line in stderr.splitlines():

使用subprocess.check_output调用gpg,并根据其输出中断循环。在

如下所示(未经测试,因为我对gpg一无所知):

import subprocess

dictionaryfile = "/root/john.txt"
pgpencryptedfile = "helloworld.txt.gpg"

with open(dictionaryfile, 'r') as f:
    for line in f:
        x = line.rstrip('\n')
        cmd = ["echo " + x + " | gpg  passphrase-fd 0 " + pgpencryptedfile]
        output = subprocess.check_output(cmd, shell=True)
        if 'gpg: WARNING: message was not integrity protected' in output:
            break

您可以使用subprocess模块,该模块允许您使用:

subprocess.call(args, *, stdin, stdout, stderr, shell)

(有关如何使用参数,请参阅Python Documentation。)

这很好,因为你可以很容易地读入你调用的任何程序的退出代码。在

例如,如果将“newstring”更改为:

^{pr2}$

如果有匹配项,grep将返回0;如果找到不匹配项,则返回1。(Source

grep的退出代码将从subprocess.call()函数,您可以轻松地将其存储在变量中并使用if语句。在

编辑:正如马修·亚当斯在下面提到的,你也可以阅读gpg本身的退出代码。在

相关问题 更多 >