Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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 为什么这个正则表达式不起作用?_Python_Regex_Netcat - Fatal编程技术网

Python 为什么这个正则表达式不起作用?

Python 为什么这个正则表达式不起作用?,python,regex,netcat,Python,Regex,Netcat,以下是相关代码: import subprocess import re import os p = subprocess.Popen(["nc -zv 8.8.8.8 53"], stdout=subprocess.PIPE, shell = True) out, err = p.communicate() regex = re.search("succeeded", out) if not regex: print ("test") 我希望它做的是,如果正则表达式与netcat命

以下是相关代码:

import subprocess
import re
import os
p = subprocess.Popen(["nc -zv 8.8.8.8 53"], stdout=subprocess.PIPE, shell = True)
out, err = p.communicate()

regex = re.search("succeeded", out)
if not regex:
    print ("test")
我希望它做的是,如果正则表达式与netcat命令不匹配,则打印出test。现在我只需要匹配“成功”,但这就是我所需要的,因为netcat命令会输出:

Connection to 8.8.8.8 53 port [tcp/domain] succeeded!

代码运行正常,但在不应该的情况下匹配

输出是标准输出,而不是标准输出:

stderr=subprocess.PIPE
您可以简化为在中使用,而不需要shell=True:

p = subprocess.Popen(["nc", "-zv", "8.8.8.8", "53"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

if "succeeded" not in err:
    print ("test")
您还可以将stderr重定向到STDOUT并使用check_输出,假定您使用的是python>=2.7:

out = subprocess.check_output(["nc", "-zv", "8.8.8.8", "53"],stderr=subprocess.STDOUT)

if "succeeded" not in out:
    print ("test")