[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

The grid5-data2.txt datafile has the same dimensions but contains expressions in two
of its columns, not just simple numbers. Because this script converts input field values
with the Python eval built-in function, any Python syntax will work in this table’s fields,
as long as it can be parsed and evaluated within the scope of the onSum method:


C:\...\PP4E\Gui\Tour\Grid> type grid5-data2.txt
1 2 3 2*2 5 6
1 3-1 3 2<<1 5 6
1 5%3 3 pow(2,2) 5 6
1 2 3 2**2 5 6
1 2 3 [4,3][0] 5 6
1 {'a':2}['a'] 3 len('abcd') 5 6
1 abs(-2) 3 eval('2+2') 5 6

Summing these fields runs the Python code they contain, as seen in Figure 9-40. This
can be a powerful feature; imagine a full-blown spreadsheet grid, for instance—field
values could be Python code “snippets” that compute values on the fly, call functions
in modules, and even download current stock quotes over the Internet with tools we’ll
meet in the next part of this book.


Figure 9-40. Python expressions in the data and table


It’s also a potentially dangerous tool—a field might just contain an expression that
erases your hard drive!† If you’re not sure what expressions may do, either don’t use
eval (convert with more limited built-in functions like int and float instead) or make
sure your Python is running in a process with restricted access permissions for system
components you don’t want to expose to the code you run.


Of course, this still is nowhere near a true spreadsheet program. There are fixed column
sums and file loads, for instance, but individual cells cannot contain formulas based


† I debated showing this, but since understanding a danger is a big part of avoiding it—if the Python process
had permission to delete files, passing the code string import('os').system('rm –rf *') to eval on Unix
would delete all files at and below the current directory by running a shell command (and 'rmdir /S /Q .'
would have a similar effect on Windows). Don’t do this! To see how this works in a less devious and potentially
useful way, type import('math').pi into one of the GUI table’s cells—on Sum, the cell evaluates to pi
(3.14159). Passing "import('os').system('dir')" to eval interactively proves the point safely as well.
All of this also applies to the exec built-in—eval runs expression strings and exec statements, but expressions
are statements (though not vice versa). A typical user of most GUIs is unlikely to type this kind of code
accidentally, of course, especially if that user is always you, but be careful out there!


Grids | 581
Free download pdf