从子进程outpu中查找以特殊单词开头的字符串

2024-04-24 04:08:49 发布

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

在代码中,我正在搜索以FAILED开头的字符串。 tt变量保存subprocess.Popen的stdoutput。 我尝试过re.serach&;re.match,但它产生{}作为返回值。在

#!/usr/bin/python
import subprocess
import re

def cbk():
    with open('GDPC.txt', 'r') as f:
        for line in f:
            tt = subprocess.Popen(['/grid/it/bin/cyberarksdk.sh' ,  'chk', line], stdout=subprocess.PIPE).communicate()[0]
            #pat_match=re.search(".*FAILED:\s+", tt)
            pat_match=re.search(r'(^FAILED:)\s+', tt)
            print pat_match

cbk()

Output of the above script:

^{pr2}$

The output of the Variable tt:

FAILED: Account/host myserver1 does not exist inside cyberark.
1 102_2923 DS-KS-DEFAULT-UNIX-ROOT Operating System-DS-Unix-RootAccounts-SSH-myserver2-root

意图:只需搜索以FAILED字符串开头的行,并剪切第三列myserevr1并放入文件file1,类似地,任何以1开头的行都将myserver2剪切并放入另一个文件file2。在

注意:GDPC.txt包含服务器名称。在


Tags: 字符串importretxtsearchbinmatchline
1条回答
网友
1楼 · 发布于 2024-04-24 04:08:49

我现在得到的解决方案是得到包含FAILED的行

#!/usr/bin/python
import subprocess
import re
##################
def cbk():
    with open('GDPC.txt', 'rw') as f:
        for line in f:
            tt = subprocess.Popen(['/grid/it/bin/cyberarksdk.sh' ,  'chk', line], stdout=subprocess.PIPE).communicate()[0]
            pm = re.search('FAILED.*', tt)
            if pm:
                 #print  pm.group(0)
                 for line in pm.group(0).splitlines():
                     col = line.split()
                     if len(col) >=3:
                         print col[2]
cbk()

Below is the output :

^{pr2}$

Solution: Borrowed from https://stackoverflow.com/a/7831312/7995721

使用split()和splitlines()(将字符串转换为行列表,将行列表转换为列列表,然后根据需要为这些列编制索引):

相关问题 更多 >