我有点问题。出于某种原因,我试图放在一起的这个类是抛出一个NoneType错误,因为就所有意图和目的而言,它应该正确地响应,就我所知。
import re
import subprocess
class progEnv( object ) :
hostName_regex = re.compile( '[a-z][a-z]prog[a-z][a-z][a-z]\d\d' )
hostDomain_regex = re.compile( '(prod|dev|qa1|stag)\.company\.net' )
hostNum_regex = re.compile( '[a-z][a-z]prog[a-z][a-z][a-z](\d\d)' )
hostPrefix_regex = re.compile( '\w\wprog' )
hostTier_regex = re.compile( '(web|app)' )
hostId_regex = re.compile( '[a-z][a-z]prog[a-z][a-z][a-z]\d\d([a-z])' )
hostEnv_regex = re.compile( '(prod|dev|qa1|stag)' )
def __init__( self ) :
self.hostnameProc = subprocess.Popen( 'hostname', stdout=subprocess.PIPE )
self.fqdn = self.hostnameProc.stdout.read()
self.hostName = self.hostName_regex.search( self.fqdn )
self.hostDomain = self.hostDomain_regex.search( self.fqdn )
self.hostNum = self.hostNum_regex.search( self.hostName.group() )
self.hostPrefix = self.hostPrefix_regex.search( self.hostName.group() )
self.hostTier = self.hostTier_regex.search( self.hostName.group() )
self.hostId = self.hostId_regex.search( self.hostName.group() )
self.hostEnv = self.hostEnv_regex.search( self.hostName.group() )
当我实例化progEnv类时,程序在调用self.hostName.group()
时失败,错误为:
Traceback (most recent call last):
File "./test.py", line 5, in <module>
env = prog_env.progEnv()
File "/prog/eclipse/workspace/PROG Management Command/prog_env.py", line 28, in __init__
self.hostNum = self.hostNum_regex.search( self.hostName.group() )
AttributeError: 'NoneType' object has no attribute 'group'
有关正在发生的事情的任何想法?
答案 0 :(得分:3)
这意味着正则表达式不匹配,因此self.hostName_regex.search(self.fqdn)
返回None
。当然,您无法在.group()
上使用None
方法。
答案 1 :(得分:0)
错误消息显示您正在尝试访问group
的属性None
。从显示的代码行开始,self.hostName
必须为None
。用于初始化self.hostName
的正则表达式搜索必定无法匹配任何内容。
AttributeError
:AttributeError的错误消息显示了对象的类型,None
的类型是NoneType
。
答案 2 :(得分:0)
self.hostName = self.hostName_regex.search( self.fqdn )
当None
与正则表达式不匹配时,此行将self.hostName的值设置为self.fqdn
。这是导致错误的原因。将依赖行更改为,
self.hostNum = self.hostName and self.hostNum_regex.search( self.hostName.group() )
在使用group
方法之前检查self.hostName。