如何查看Python源代码的符号表?
我的意思是,在实际运行程序之前,Python会为每个程序创建一个符号表。那么我的问题是,如何将该符号表作为输出获取?
如何查看Python源代码的符号表?
我的意思是,在实际运行程序之前,Python会为每个程序创建一个符号表。那么我的问题是,如何将该符号表作为输出获取?
Python的特性是动态而非静态。虚拟机具有可寻址命名空间,而不是编译对象代码中的符号表,用于存储变量。
dir()
或dir(module)
函数返回代码在该点处的有效命名空间。它主要用于交互式解释器,但也可以被代码使用。它返回一个字符串列表,其中每个字符串都是带有某些值的变量。
globals()
函数返回一个变量名到变量值的字典,其中变量名在该时刻被认为是全局范围内的。
locals()
函数返回一个变量名到变量值的字典,其中变量名在该时刻被认为是局部范围内的。
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import base64
>>> dir(base64)
['EMPTYSTRING', 'MAXBINSIZE', 'MAXLINESIZE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_b32alphabet', '_b32rev', '_b32tab', '_translate', '_translation', '_x', 'b16decode', 'b16encode', 'b32decode', 'b32encode', 'b64decode', 'b64encode', 'binascii', 'decode', 'decodestring', 'encode', 'encodestring', 'k', 're', 'standard_b64decode', 'standard_b64encode', 'struct', 'test', 'test1', 'urlsafe_b64decode', 'urlsafe_b64encode', 'v']
symtable
模块。此外,Eli Bendersky撰写的这两篇文章非常有趣且详细:def describe_symtable(st, recursive=True, indent=0):
def print_d(s, *args):
prefix = ' ' *indent
print prefix + s + ' ' + ' '.join(args)
print_d('Symtable: type=%s, id=%s, name=%s' % (
st.get_type(), st.get_id(), st.get_name()))
print_d(' nested:', str(st.is_nested()))
print_d(' has children:', str(st.has_children()))
print_d(' identifiers:', str(list(st.get_identifiers())))
if recursive:
for child_st in st.get_children():
describe_symtable(child_st, recursive, indent + 5)
symtable
模块。def describe_symtable(st, recursive=True, indent=0):
def print_d(s, *args):
prefix = ' ' * indent
print(prefix + s, *args)
assert isinstance(st, symtable.SymbolTable)
print_d('Symtable: type=%s, id=%s, name=%s' % (
st.get_type(), st.get_id(), st.get_name()))
print_d(' nested:', st.is_nested())
print_d(' has children:', st.has_children())
print_d(' identifiers:', list(st.get_identifiers()))
if recursive:
for child_st in st.get_children():
describe_symtable(child_st, recursive, indent + 5)
describe_symtable
似乎是为Python3编写的。 - voithos