Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Regex从子流程输出中查找以特殊字开头的字符串_Python_Regex - Fatal编程技术网

Python Regex从子流程输出中查找以特殊字开头的字符串

Python Regex从子流程输出中查找以特殊字开头的字符串,python,regex,Python,Regex,在代码中,我正在搜索以FAILED开头的字符串。 tt变量保存子进程.Popen的stdoutput。 我尝试了re.serach和re.match,但它返回值为None #!/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/b

在代码中,我正在搜索以
FAILED
开头的字符串。
tt
变量保存
子进程.Popen的stdoutput
。 我尝试了
re.serach
re.match
,但它返回值为
None

#!/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()
上述脚本的输出:

变量
tt
的输出:

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


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

我现在得到的解决方案是获取包含
的行失败的

#!/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()
以下是输出:

解决方案:借鉴


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

是否执行
pat_match=re.search(r'(^FAILED:)\s+,tt,re.MULTILINE)
工作?@Jan,让我检查一下。@Jan,否。。它仍然在返回结果中给出相同的
None
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
#!/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()
$./cyberCheck.py
myserver1 
myserver2 
myserver3