在我正在编写的程序(一个基于文本的rpg)中,我将包括“脚本”,这些小代码为游戏添加了交互功能(例如当你进入房间时NPC会向你致意)。编写自己的脚本语言/解析器似乎是一项相当大的任务,因此我认为应该使用Python代码本身。它可以做任何我需要的脚本,所以我开始黑客。对于打印语句或数学之类的简单事情,exec()工作正常。当我遇到障碍时,麻烦就来了。这就是它的作用:
第一个工作代码(来自交互式shell):
>>> x = ''
>>> y = []
>>> while x != '@':
y.append(x)
x = raw_input(compile('''''', '<string>', 'exec'))
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>name = 'Drew'
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>print 'Hello, %s' % name
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>@
>>> del x[0] # removes the empty field created by the first y.append(x)
>>> for line in y:
exec line
>>> Hello, Drew
现在对于错误(再次从交互提示):
>>> x = ''
>>> y = []
>>> while x != '@':
y.append(x)
x = raw_input(compile('''''', '<string>', 'exec'))
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>name = 'Drew'
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>if name == 'Drew':
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>print 'Hi, %s!' % name
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>else:
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>print 'Greetings, stranger.'
<code object <module> at 0000000002B1DBB0, file "<string>", line 1>@
>>> del y[0]
>>> for line in y:
exec line
Traceback (most recent call last):
File "<pyshell#308>", line 2, in <module>
exec line
File "<string>", line 1
if name == 'Drew':
^
SyntaxError: unexpected EOF while parsing
如您所见,:字符(对于选择块是必需的)导致exec出错。我能做些什么来解决这个问题吗?我已经试了好几个小时想避开这个问题,但我似乎想不出来。难道这根本不可能吗?
非常感谢您阅读本文,我感谢您对我的帮助。
最佳答案
从空闲编辑窗口运行时,在2.7中可以执行以下操作:
line=''
lines = []
print "Enter Python lines (@ to quit):"
while line != '@':
line=raw_input()
lines.append(line)
lines.pop() # delete '@' line
lines = '\n'.join(lines)
exec lines
Shell窗口中的结果:
>>>
Enter Python lines (@ to quit):
name = 'Terry'
if name == 'Drew':
print 'Hi Drew'
else:
print 'Hi stranger'
@
Hi stranger
请注意,行需要用“\n”连接,而不是“”连接。此外,加入后,代码段不会以'\n'结尾。我相信这可能是早期版本的Python的问题,exec可能需要一个用于多行块的终端'\n'。
也就是说,这是一个可怕的方式输入代码。我花了三次努力才毫无错误地进入上面的内容!例如,对于初始输入和编辑来说,tkinter文本框小部件会更好。