【问题标题】:Python3 subprocess and if elif else conditionPython3 子进程和 if elif else 条件
【发布时间】:2018-09-24 10:54:10
【问题描述】:

在生成用户 ID 信息的运行脚本下方,但是在搜索我有多个用户的文件时,它还会打印不存在的用户名,无法在 Linux 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。但是它也返回user1 Failed: User does not exists in the Group,因为这是我在 else 语句中所要求的。

我们可以通过if, elif, else 得到它吗?比如:

如果找到单词然后"Sucess : user is in group",elif 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  

期望的输出:

user1: No such user
user30 Success: User exists in the Group 
user81 Success: User exists in the Group 

【问题讨论】:

    标签: python-3.x subprocess popen


    【解决方案1】:

    您假设id 将消息写入标准输出。但是,实际上它是写到stderr中的。

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

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

    【讨论】:

    • 感谢伟大的输入,但我可以如何调整我的代码。
    • 添加 stderr=PIPE 不会在终端上,但会保持在 else 状态:-)
    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2017-05-03
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多