0

我想捕获archlinux的pacman包管理器的输出。这样做时,我想处理它的输出,但也想向用户显示它。

到目前为止,我带来了什么:-

import subprocess as sb
import sys

lol = sb.Popen('sudo pacman -Syy',stdout=sb.PIPE,shell=True)

while True:
    l = lol.stdout.readline().strip()

    if not l and lol.poll() is not None:
        break

    sys.stdout.write(l.decode())
    sys.stdout.flush()

但它会打印:-

❯ python test.py
:: Synchronizing package databases...downloading core.db...downloading extra.db...downloading community.db...downloading multilib.db...done

这就是我想要的

:: Synchronizing package databases...
 core                                                                     135.2 KiB   160 KiB/s 00:01 [############################################################] 100%
 extra                                                                   1706.7 KiB   470 KiB/s 00:04 [############################################################] 100%
 community                                                                  4.9 MiB  1107 KiB/s 00:05 [############################################################] 100%
 multilib                                                                 161.2 KiB  3.09 MiB/s 00:00 [############################################################] 100%

done
4

2 回答 2

1

这样的事情可能对你有用:

import subprocess
import sys

# for py3 uncomment next line
# basestring = str


def cmd2args(cmd):
    """On linux we might need to split the command before executing...?
    """
    win32 = sys.platform == 'win32'
    if isinstance(cmd, basestring):
        if not win32 and cmd.startswith('cd '):
            return cmd
        else:
            return cmd if win32 else shlex.split(cmd)
    return cmd



def echorun(cmd, curdir='.'):
    """Send stderr to terminal, but yield stdout one line at a time.
    """
    popen = subprocess.Popen(cmd2args(cmd),
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             cwd=curdir,
                             shell=sys.platform == 'win32',
                             universal_newlines=True)
    if popen.stdout is not None:
        for line in iter(popen.stdout.readline, ""):
            if sys.version_info.major == 3 and isinstance(line, str):
                yield  line
            else:
                yield line.decode()

    exitcode = popen.wait()
    if exitcode != 0:
        raise RuntimeError("Exitcode: %d" % exitcode)

用法是:

    for line in echorun('sudo pacman -Syy', curdir):
        print(line)
于 2020-06-09T19:30:58.253 回答
0

这是你要找的吗?

import subprocess as sb
import sys

lol = sb.Popen('sudo pacman -Syy',stdout=sb.PIPE,shell=True)

while True:
    l = lol.stdout.readline().strip()
    if lol.poll() is not None:
        break

    sys.stdout.write(l.decode())
    sys.stdout.flush()

print("done")

输出:

:: Synchronizing package databases...downloading core.db...downloading extra.db...downloading community.db...done
于 2020-06-09T19:29:42.263 回答