Python3子流程,如果没有其他条件

时间:2018-09-24 10:54:11

标签: python-3.x subprocess popen

正在生成用户ID信息的正在运行的脚本下面,但是在搜索我有多个用户的文件时,它还会打印的用户名不存在,无法在Linux ... <dxc:BarSideBySideSeries2D.Points> <dxc:SeriesPoint Argument="A" Value="1" /> <dxc:SeriesPoint Argument="B" Value="2" /> <dxc:SeriesPoint Argument="C" Value="3" /> <dxc:SeriesPoint Argument="D" Value="4" /> </dxc:BarSideBySideSeries2D.Points> ... 命令中解析,例如:

id

情况

from subprocess import Popen, PIPE

CRED = '\033[91m'
CGRN = '\033[92m'
CEND = '\033[0m'

with open("kkdiff", "r") as lid:
    for line in lid:
        line = line.strip()
        proc = Popen(['id', line], stdout=PIPE,)
        myID = proc.communicate()[0].decode('utf-8')
        if re.search(r'\bkoint\b', myID):
            print(line, CGRN + "Success: " + CEND + "User exists in the Group")
        else:
            print(line, CRED + "Failed: " + CEND + "User does not exists in the Group")

因此,在将id <username> results <no such user> #id: user1: No such user <-- This is ideal in Linux systems 命令与python子进程模块一起使用时,它将在终端上返回相同的id。但是,它还会返回#id: user1: No such user,因为这是我在else语句中所要求的。

我们可以通过user1 Failed: User does not exists in the Group来获得它吗?

如果找到了单词,则依次为if, elif, else,elif "Sucess : user is in group"no such user,否则为"User is not the AD"

脚本输出:

"Failed: user is not in group"

所需的输出:

id: user1: No such user
user1 Failed: User does not exists in the Group
user30 Success: User exists in the Group 
user81 Success: User exists in the Group  

1 个答案:

答案 0 :(得分:1)

您已假设id将消息写入stdout。但是,实际上,它已将其写入stderr。

$ id foo >/dev/null
id: ‘foo’: no such user
$ id foo 2>/dev/null
(empty output)

要访问Popen进程的stderr,请使用proc.communicate()[1]