我想做一个你可以写其他程序的程序

2024-04-26 21:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题exec在处理代码的组合字符串时,它返回了一个错误:函数“python”中的unqualified exec它是一个嵌套函数

有时,它不会返回错误,而是不会产生任何输出。你知道吗

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()

Tags: 函数代码infor错误coderangeprompt
1条回答
网友
1楼 · 发布于 2024-04-26 21:30:39

你为什么要这样直接操纵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中不起作用。你知道吗

相关问题 更多 >