前两个args对于compile()python3的意义

时间:2014-01-01 06:06:30

标签: python

我正在努力扩展我对python的各种内置模块的理解,我遇到了compile()。 我创建了一个名为program.py的文件,它返回print("hello")。我打算将来使用(从看似)compile()exec程序中的其他程序。

我的问题是前两个论点有什么意义?我了解第三种选择可以是以下三种选择之一:execevalsingle

如果有人理解compile()命令,请帮助我。

import program

compile('','','exec',flags=0,dont_inherit=False,optimize=-1)
# compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) - are the args

2 个答案:

答案 0 :(得分:0)

第一个是要编译的Python源代码。第二个是在追溯中显示的文件名。

>>> compile('foo', 'bar', 'exec')
<code object <module> at 0x7fb586b57ab0, file "bar", line 1>
>>> exec(compile('foo', 'bar', 'exec'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bar", line 1, in <module>
NameError: name 'foo' is not defined

答案 1 :(得分:0)

  1. source - 可以是Unicode字符串或Latin-1编码字符串。即compile('a + 5','', 'eval')

  2. filename参数应该给出代码所在的文件 读;如果没有从文件中读取,则传递一些可识别的值(通常使用“字符串”)。

  3. 因此,如果你想编译一个文件,第一个值将是一个空字符串,第二个值将指定文件名,如果你想编译一个字符串,第一个值将是字符串,第二个值将是空字符串。