使用exec()和用户定义的字符串--If语句?

时间:2013-04-21 18:03:25

标签: python python-3.x

仅仅为了实验,我想看看我是否可以创建一个用户可以输入字符串的程序,然后可以将其作为Python代码执行。但是,我似乎无法使if / while / for语句正常工作。那么,有没有一种方法可以解决这个问题呢?

我的源代码:

prog = []

while True:
    varCommand = input(':')
    if varCommand == 'shell':
        code = ' '
        while code[len(code)-1] != 'end':
            code = [input('>>>>')]
            prog += code
        del prog[len(prog)-1]

    if varCommand == 'run':
        for i in range(len(prog)):
            exec(prog[i])

    if varCommand == 'view':
        for i in range(len(prog)):
            print('>>>>' + prog[i])

    if varCommand == 'delete':
        prog = []

例如,如果我尝试这样做:

for i in range(1,11):

尝试使用上述程序运行该操作会导致运行时错误,由于EOF,指向冒号。有没有办法使这项工作?

1 个答案:

答案 0 :(得分:1)

问题在于:

if varCommand == 'run':
    for i in range(len(prog)):
        exec(prog[i])

使用此循环会导致程序运行用户一次输入一行的内容。所以第一个exec只能看到for循环,并且不知道有什么东西在它之后。 exec需要查看输入的全部代码。

你想要的是执行一次输入的所有内容,每个字符串用换行符分隔。将以上内容替换为:

if varCommand == 'run':
    exec('\n'.join(prog))

所以我现在可以做

:shell
>>>>for i in range(10):
>>>>    print(i)
>>>>
>>>>end
:run
0
1
2
3
4
5
6
7
8
9