2013-04-21 61 views
0

只是为了进行实验,我想看看是否可以制作一个程序,用户可以输入字符串,然后可以将其作为Python代码执行。但是,我似乎无法得到if/while/for语句正常工作。那么,有没有这样做的方法,我失踪了?使用exec()和用户定义的字符串 - If语句?

我的源代码:

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

的问题是在这里:

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 
+0

这工作,非常感谢你。 :) – kanokarob 2013-04-21 18:16:27