由sqlmap学到的python杂烩
1. global
2. hasattr 和 dict.xxx的区别
global:
声明变量为全局变量,此关键字为跨函数的,但不跨文件。如果要跨文件,还是得用from XXX import XXX
例如:
config = None
def configFileProxy(section, option, boolean=False, integer=False):
"""
Parse configuration file and save settings into the configuration
advanced dictionary.
"""
global config
if config.has_option(section, option):
try:
if boolean:
value = config.getboolean(section, option) if config.get(section, option) else False
elif integer:
value = config.getint(section, option) if config.get(section, option) else 0
else:
value = config.get(section, option)
except ValueError, ex:
errMsg = "error occurred while processing the option "
errMsg += "'%s' in provided configuration file ('%s')" % (option, str(ex))
raise SqlmapSyntaxException(errMsg)
if value:
conf[option] = value
else:
conf[option] = None
else:
debugMsg = "missing requested option '%s' (section " % option
debugMsg += "'%s') into the configuration file, " % section
debugMsg += "ignoring. Skipping to next."
logger.debug(debugMsg)
上面的config是global的,函数外有定义。
而logger,conf等变量是import进来的
hasattr 和 dict.xxx
hasattr是不会抛异常的,如果存在返回true,如果不存在返回false,而dict.xxx如果不存在会出error
例如:
if hasattr(conf, "api"):
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype="stdout")
sys.stderr = StdDbOut(conf.taskid, messagetype="stderr")
setRestAPILog()
.......
if conf.profile:
profile()