Python3中exec()的反义是什么?

时间:2018-02-27 19:09:59

标签: python string expression exec repr

我正在尝试使用它们的评估来打印表达式列表的字符串表示。

输入

def info():
    return [
    __name__,
    type(__name__),
    inspect.currentframe(),
    inspect.getframeinfo(inspect.currentframe())
    ]


#my attempt 
for a in map(str, info()):
    print("{}: {}\n".format(str(a), a))

输出

__main__: __main__

<class 'str'>: <class 'str'>

<frame object at 0x0ED881C0>: <frame object at 0x0ED881C0>

Traceback(filename='<ipython-input-23-1812d70522a0>', lineno=7,function='info', code_context=['    inspect.getframeinfo(inspect.currentframe())]\n'], index=0): Traceback(filename='<ipython-input-23-1812d70522a0>', lineno=7, function='info', code_context=['    inspect.getframeinfo(inspect.currentframe())]\n'], index=0)

预期结果

__name__:  __main__

type(__name__):  <class 'str'>

inspect.currentframe(): <frame object at 0x0ED881C0>

inspect.getframeinfo(inspect.currentframe(): Traceback(filename='.......

有没有办法做我想做的事情?

2 个答案:

答案 0 :(得分:1)

这个答案假设源代码在一个文件中,而不是在python控制台中运行,否则它将无法工作。

您可以使用inspect.getsourcelines()做您想做的事情:

import inspect

def info():
    return [
    __name__,
    type(__name__),
    inspect.currentframe(),
    inspect.getframeinfo(inspect.currentframe())
    ]

lines = inspect.getsourcelines(info)

# This removes the undesired def info() and following line
lines = lines[0][2:]

i = 0
for a in map(str, info()):
    print("{}: {}\n".format(lines[i].replace('\n', ''), a))
    i += 1

输出:

__name__,: __main__

type(__name__),: <class 'str'>

inspect.currentframe(),: <frame object at 0x00000000013C7758>

inspect.getframeinfo(inspect.currentframe()): Traceback(filename='C:/Users/czimmerman/PycharmProjects/census_data/data/test.py', lineno=8, function='info', code_context=['    inspect.getframeinfo(inspect.currentframe())\n'], index=0)

答案 1 :(得分:-1)

使用某些代码检查或回溯模块可能是一种复杂的方法。但即使你使它工作也不会很好地概括,并且它可能无法与所有python发行版一起工作。

在尝试将任何表达式添加到列表之前,python将评估该表达式。因此,你无法在没有黑客的情况下获得表达。但是,您可以做的是将表达式字符串存储在列表中并使用exec执行它们。所以你的代码变得更容易编写。

所以请确保你绝对需要这个。如果你这样做,那么这比它看起来更复杂