<p>如果输入是安全的(它来自受信任方),则可以使用eval,它接受一个包含Python代码的字符串,对其求值并返回结果。在</p>
<p>例如:</p>
<pre><code>from __future__ import print_function
from collections import namedtuple
from pprint import pprint
import sys
# Read the entire file to a list of lines
with open('my_text.txt', 'r') as f:
lines = f.readlines()
# Declare a Piece class, which is a named tuple (immutable)
Piece = namedtuple('Piece', ['color', 'piece'])
# The cases dictionary where we will write
cases = {}
# For lines 4 to last, counting them starting at 4...
for num_line, line in enumerate(lines[3:], start=4):
try:
# Evaluate the line (will return a tuple)
a_tuple = eval(line)
# Separate the first element from the rest
key, params = a_tuple[0], a_tuple[1:]
# Write in the dictionary. *params is substituted with an argument for
# each element in the tuple params.
cases[key] = Piece(*params)
except:
# If something was wrong, print the line that failed in the text file
# and raise the exception to get the traceback and stop the program.
print("Failed to parse line %d: %s" % (num_line, line), file=sys.stderr)
raise
# Pretty print the result
pprint(cases)
</code></pre>