📄 index.lxp@lxpwrap=c6996_252ehtm.htm
字号:
<TTCLASS="VARNAME">locals</TT>.</P><P>By default, the <TTCLASS="VARNAME">globals</TT> and <TTCLASS="VARNAME">locals</TT> arguments of <TTCLASS="FUNCTION">eval()</TT>, <TTCLASS="FUNCTION">exec()</TT> and <TTCLASS="FUNCTION">execfile()</TT> contain the current contents of <TTCLASS="VARNAME">globals</TT> and <TTCLASS="VARNAME">locals</TT>, but you can alter this— for instance, to restrict access to certain application objects.</P><DIVCLASS="SECT2"><H2CLASS="SECT2">Playing with <TTCLASS="FUNCTION">eval()</TT></A></H2><P><TTCLASS="FUNCTION">eval()</TT> functions as if it executes a single line of code in the Python interpreter: it returns a value that represents the result of the evaluated expression. If the statement you give to <TTCLASS="FUNCTION">eval()</TT> raises an exception, the surrounding code gets that exception, too. Playing around with <TTCLASS="FUNCTION">eval()</TT> will give you a feeling for what it can do for you.</P><DIVCLASS="FIGURE"></A><P><B>Figure 20-1. Playing with <TTCLASS="FUNCTION">eval()</TT></B></P><PRECLASS="SCREEN">boud@calcifer:~/doc/pyqt/ch15 > pythonPython 2.0 (#1, Mar 1 2001, 02:42:21)[GCC 2.95.2 19991024 (release)] on linux2Type "copyright", "credits" or "license" for more information.>>> eval<built-in function eval>>>> eval("1==1")1>>> import string>>> eval("string.split('bla bla bla')")['bla', 'bla', 'bla']>>> eval("string.split('bla bla bla')", {}, {})Traceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 0, in ?NameError: There is no variable named 'string'>>> eval("""from qt import *... s=QString("bla bla bla")... print str(s).split()... """)Traceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 1 from qt import * ^SyntaxError: invalid syntax>>> </PRE></DIV><P>First, we take a look at what "eval" is for a beast. A built-in function. OK, let's try it out. Yes, 1 equals 1 evaluates to 1, which means TRUE - <TTCLASS="FUNCTION">eval</TT> neatly returns the result of the code it executes. Next, having imported the <TTCLASS="FILENAME">string</TT> module, we use it to split a string. Here, <TTCLASS="FUNCTION">eval()</TT> has access to the global namespace, which means it can access the module we just imported, so <TTCLASS="FUNCTION">string.split()</TT> evaluates just fine. However, if we try to evaluate the same expression, but with empty global and local dictionaries, we get a <TTCLASS="VARNAME">NameError</TT> exception - suddenly <TTCLASS="FUNCTION">string</TT> isn't known anymore. Trying to evaluate something more complicated, something that is not a single expression that returns a value (even if it's only <TTCLASS="VARNAME">None</TT>) doesn't work at all - which is why <TTCLASS="FUNCTION">exec()</TT> exists.</P></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2">Playing with <TTCLASS="FUNCTION">exec</TT></A></H2><P>First, <TTCLASS="FUNCTION">exec</TT> is really a statement, not a function, so it doesn't return anything. Just as with <TTCLASS="FUNCTION">eval()</TT>, exceptions are propagated outside the code block you execute. You can feed <TTCLASS="FUNCTION">exec</TT> a string, a compiled code object or an open file. The file will be parsed until an EOF (end-of-file) occurs, and executed. The same rules hold for the global and local namespace dictionaries as with <TTCLASS="FUNCTION">eval()</TT> - but keep in mind that running <TTCLASS="FUNCTION">exec</TT> might add new items to those namespaces.</P><DIVCLASS="FIGURE"></A><P><B>Figure 20-2. Playing with <TTCLASS="FUNCTION">exec</TT></B></P><PRECLASS="SCREEN">boud@calcifer:~/doc/pyqt/ch15 > pythonPython 2.0 (#1, Mar 1 2001, 02:42:21)[GCC 2.95.2 19991024 (release)] on linux2Type "copyright", "credits" or "license" for more information.>>> globals(){'__doc__': None, '__name__': '__main__', '__builtins__': <module '__builtin__' (built-in)>}>>> code = """... import qt... s = qt.QString("bla bla bla")... print string.split(str(s))... """>>> exec codeTraceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 4, in ?NameError: There is no variable named 'string'>>> import string>>> exec code['bla', 'bla', 'bla']>>> globals(){'__doc__': None, 'string': <module 'string' from'/usr/lib/python2.0/string.pyc'>, '__name__': '__main__', '__builtins__': <module '__builtin__' (built-in)>, 'qt': <module 'qt' from'/usr/lib/python2.0/site-packages/qt.py'>, 'code': '\012import qt\012s = qt.QString("bla bla bla")\012printstring.split(str(s))\012', 's': <qt.QString instance at 0x8278af4>}>>> </PRE></DIV><P>First, we create a string that contains the bit of Python we want to execute. Note how it imports the <TTCLASS="FILENAME">qt</TT> module, and how it uses the <TTCLASS="FILENAME">string</TT> module. Executing the code doesn't work: it throws a <TTCLASS="VARNAME">NameError</TT> because <TTCLASS="FILENAME">string</TT> isn't known. Importing <TTCLASS="FILENAME">string</TT> into the global namespace makes it also available to <TTCLASS="FUNCTION">exec</TT>, of course. Executing the <TTCLASS="VARNAME">code</TT> string now succeeds, and a quick peek in <TTCLASS="VARNAME">globals</TT> learns us that the module <TTCLASS="FILENAME">qt</TT> has been added.</P></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2">Playing with <TTCLASS="FUNCTION">execfile()</TT></A></H2><P>The <TTCLASS="FUNCTION">execfile()</TT> statement is rarely used; after all, it can't do anything beyond what the plain <TTCLASS="FUNCTION">exec</TT> statement already does. <TTCLASS="FUNCTION">execfile()</TT> functions exactly the same as <TTCLASS="FUNCTION">exec</TT>, except that the first argument must be a filename (it doesn't need to be an open file object). Note that <TTCLASS="FUNCTION">execfile()</TT> differs from <TTCLASS="LITERAL">import</TT> in that it doesn't create a new module in the global namespace. Note the difference between <TTCLASS="FUNCTION">execfile()</TT> and <TTCLASS="LITERAL">import</TT> in the following output:</P><DIVCLASS="FIGURE"></A><P><B>Figure 20-3. Playing with <TTCLASS="FUNCTION">execfile()</TT></B></P><PRECLASS="SCREEN">Python 2.0 (#1, Mar 1 2001, 02:42:21)[GCC 2.95.2 19991024 (release)] on linux2Type "copyright", "credits" or "license" for more information.>>> execfile("main.py")Initializing configuration{'kalam': <kalamapp.KalamApp instance at 0x825f014>, 'app': <qt.QApplication instance at 0x814a2a4>, 'args': ['']}Saving configuration>>> import main>>> globals(){..., 'main': <module 'main' from 'main.py'>, ... } </PRE></DIV><P>In the middle of all the <TTCLASS="FILENAME">qt</TT> classes the <TTCLASS="FILENAME">main</TT> module of <SPANCLASS="APPLICATION">Kalam</SPAN> imports into <TTCLASS="VARNAME">globals</TT>, we find the <TTCLASS="FILENAME">main</TT> module itself, which isn't there if we just <TTCLASS="FILENAME">execfile</TT> <TTCLASS="FILENAME">main.py</TT>.</P></DIV></DIV></DIV><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><A accesskey="P" href="index.lxp@lxpwrap=x6992_252ehtm.htm">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><A accesskey="H" href="index.lxp@lxpwrap=book1_252ehtm">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><A accesskey="N" href="index.lxp@lxpwrap=x7161_252ehtm.htm">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Conclusion</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><A accesskey="U" href="index.lxp@lxpwrap=p4627_252ehtm.htm">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Integrating macros with a GUI</TD></TR></TABLE></DIV></BODY></HTML> </td> </tr> </table> </td> </tr> </table>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -