
本文共 2615 字,大约阅读时间需要 8 分钟。
Python exec ���������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
1 exec()
������������
���������
1-1 ������
exec(object[, globals[, locals]])
���������������������object
������������������������������������������������������������������������������
1-2 ������
- object������������������������������������������ Python ��������������������������������� code ��������������� object ��������������������������������������������������������� Python ��������������������������������������������������������������� object ��������� code ���������������������������������������������
- globals������������������������������������������������������������������������������������������������������������������������
- locals��������������������������������������������������������������������������������������������������������������������������������������������������������������������������� globals ���������������
1-3 ���������
exec ������������������ None���
2 exec()
������������
���������������������exec()
���������������������������������������������������������������������������������������������������������bash������python���������
���������������������exec()
���������������������������
������������������������������������������������������������
2-1 ������
2-1-1 ���������������������������
>>> a = 13>>> exec('b = a + 1')>>> print(b)14
���������������������������������������exec()
������������������������������������
2-1-2 ������������������������������
>>> def test():... a = 13... exec('b = a + 1')... print(b)...>>> test()Traceback (most recent call last): File "", line 1, in File " ", line 4, in testNameError: global name 'b' is not defined>>>
������������������������������������������exec()
��������������� exec()
������������������������������������������������������������������������������
2-1-3 ���������������������������
>>> def test():... a = 13... exec('b = a + 1')... exec('print(b)')...14
���������������������������������������exec()
������������������
2-2 ������exec()
������������������������������
def test(module): exec_scope = {"module": module} exec(f"module = {module}()", exec_scope) # ���������module������ exec(f"test_result = module.test()", exec_scope) # ������module���test������ test_result = exec_scope['test_result'] # ���exec������������������������������
������������{}
������������������������������������������������������/������exec
���������
发表评论
最新留言
关于作者
