简体   繁体   English

python中的re.search()函数未找到子字符串

[英]re.search() function in python not finding substring

The substring 'Failed to connect to host' is not being found in the 'text' variable. 在'text'变量中找不到子字符串'Failed to connect to host'。 I am fairly new to python and I would appreciate any help. 我是python的新手,希望能对您有所帮助。

import subprocess
import re

host = 'XXXXXXX'
output = subprocess.Popen(['/usr/bin/ssh', '-q', host, 'ifconfig|', 'grep', 'Mask'], stdout=subprocess.PIPE)
text = output.communicate()[0].decode('utf-8')
pattern = 'Failed to connect to host'

if re.search(pattern, text, re.IGNORECASE):
    print('found')
else:
    print('not found')

The expected result should be "found" since the text str contains the pattern but for some reason, the result is "not found". 预期结果应为“找到”,因为文本str包含该模式,但由于某种原因,结果为“未找到”。

Actual Output: 实际输出:

Failed to connect to host XXXXXXX port 22: No route to host
not found

It's because the error message is printed to stderr, but you're only matching against the text printed on stdout. 这是因为错误消息被打印到stderr,但是您只匹配标准输出上打印的文本。 If you try print(repr(text)) you'll see it prints '' . 如果您尝试print(repr(text))您会看到它打印''

Try adding stderr=subprocess.STDOUT to your Popen call, like this: 尝试将stderr=subprocess.STDOUT添加到您的Popen调用中,如下所示:

output = subprocess.Popen([...], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#                                                        ^-- this

What it does is it redirects stderr to stdout. 它的作用是将stderr重定向到stdout。 See the docs here: https://docs.python.org/3.7/library/subprocess.html#subprocess.STDOUT 请参阅此处的文档: https : //docs.python.org/3.7/library/subprocess.html#subprocess.STDOUT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM