【发布时间】:2017-08-05 17:42:50
【问题描述】:
我之前问了一个问题,但遇到了第二个问题。
我正在编写一个读取文本文件并执行文件中所有代码的程序。这是上课用的,我们必须使用exec()
我在运行代码时遇到这个错误,无数次的搜索都没有让我找到解决方案。
Traceback (most recent call last):
File "doxecute.py", line 28, in <module>
replace_code(statements, contents)
File "doxecute.py", line 17, in replace_code
contents = contents.replace("{%" + statement + "%}", statement)
TypeError: Can't convert 'NoneType' object to str implicitly
代码是
import sys
import re
def sortecute(data):
funcs = re.findall(r'{%(.*?)%}',data,re.DOTALL)#find executable statements
return funcs
def replace_code(statements, contents):
for statement in statements:
if not statement[5:].startswith("print("):
exec(statement[5:]) #execute code after the (letter)
contents = contents.replace("{%" + statement + "%}", "")
else:
statement = exec(statement[5:])#error is here
contents = contents.replace("{%" + statement + "%}", statement)
print(contents)
f = open(sys.argv[1],"r")
contents = f.read()
f.close()
statements = sortecute(contents) #get data from file
statements = sorted(statements) #sorts by letter
replace_code(statements, contents)
这是我读到的文件。
The number {% (c) print(x) %} is a random number between 1 and 6
inclusive. If we multiply it by 2, we get {% (d) print(2*x) %}.
What's interesting is that the statements may appear out of order in the
document. {% (a) import random %} Thus I might generate the random
number in a location in the document well after referencing it.
{% (b) x = random.randint(1,6) %}
我不知道如何获取 exec 语句的值。有人可以向我解释如何以下面列出的方式正确使用它
You will need to use the exec function in Python. To get the output back, you will need to redirect output to your own stream. Your program should accept a filename as a command-line argument to operate on [8]
【问题讨论】:
-
print()函数不返回任何内容。 -
什么意思?我用它来调试。 @AshwiniChaudhary
-
exec在 Python 3 中总是返回None。在 Python 2 中,exec是一个语句,所以它实际上并没有返回任何东西。
标签: python python-3.x exec