我正在使用以下方法isset(var)
来确定变量是否存在。
def isset(variable):
try:
variable
except NameError:
return False
else:
return True
如果变量存在,则返回True
。但如果变量不存在,我会得到以下内容:
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/lenovo/pyth/master/vzero/__main__.py", line 26, in <module>
ss.run()
File "vzero/ss.py", line 4, in run
snap()
File "vzero/ss.py", line 7, in snap
core.display()
File "vzero/core.py", line 77, in display
stdout(session(username()))
File "vzero/core.py", line 95, in session
if isset(ghi): #current_sessions[user]):
NameError: global name 'ghi' is not defined
我不想要所有这些错误。我只想让它返回False。没有输出。我怎么能这样做?
答案 0 :(得分:2)
而不是编写复杂的辅助函数isset
并调用它
if not isset('variable_name'):
# handle the situation
在您要检查变量存在的位置:
try:
# some code with the variable in question
except NameError:
# handle the situation