【问题标题】:I would like to make a program with which you can write other programs我想制作一个程序,您可以使用它编写其他程序
【发布时间】:2023-03-17 05:10:01
【问题描述】:

我在exec处理代码的组合字符串时遇到问题,它返回错误:函数'python'中不合格的执行它是一个嵌套函数

此外,有时它不会返回错误,而是不会导致任何输出。

def python():
        prompt=">>> "
        lines=0
        fullcode=""
        enter="\n"
        print "\nPython 2.7.8"
        print "\nEnter your lines of code, when you are finished enter 'end'."
        for x in range(1,1000):
            code=raw_input(prompt)
            if "end" not in code.lower():
                globals()['line%s' % x] = code
                lines+=1
            else:
                break
        for x in range(1,lines):
            y=x+1
            fullcode+=globals() ['line%s' %x] + enter
        try:
            exec fullcode
        except:
            print "Error"
python()

【问题讨论】:

    标签: python python-2.7 global-variables exec nested-function


    【解决方案1】:

    你为什么要这样直接操作globals() dict?

    无论如何,您需要提供exec 工作的上下文。完整的形式是

    exec fullcode in globals(), locals()

    但是在你的代码中你不应该指定locals(),除非你想让用户访问在你的python函数中定义的局部变量。

    另外,你的转换循环结束得太早了,应该是

    for x in range(1, lines + 1):

    这是您的代码的编辑版本,应该可以满足您的需求:

    #! /usr/bin/env python
    
    def python():
            prompt=">>> "
            lines=0
            fullcode=""
            enter="\n"
            print "\nPython 2.7.8"
            print "\nEnter your lines of code, when you are finished enter 'end'."
            for x in range(1,1000):
                code=raw_input(prompt)
                if "end" not in code.lower():
                    globals()['line%s' % x] = code
                    lines+=1
                else:
                    break
            for x in range(1,lines+1):
                fullcode+=globals()['line%s' %x] + enter
            try:
                exec fullcode in globals() #, locals()
            except Exception, e:
                print "Error:", e
    
    python()
    

    这是您代码的另一个版本,它不会将每一行存储为globals() 中的新变量

    #! /usr/bin/env python
    
    import readline
    
    def python():
            prompt = ">>> "
            codelines = []
            print "\nPython 2.7.8"
            print "\nEnter your lines of code, when you are finished enter 'end'."
            while True:
                code = raw_input(prompt)
                if "end" not in code.lower():
                    codelines.append(code)
                else:
                    break
    
            fullcode = '\n'.join(codelines)
            #print `fullcode`
            try:
                exec fullcode #in globals(), locals()
            except Exception, e:
                print "Error:", e
    
    python()
    

    import readline 语句提供行编辑;但 IIRC 在 Windows 中不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      相关资源
      最近更新 更多