Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当我需要返回值时,exec返回一个nonetype_Python_Python 3.x_Exec - Fatal编程技术网

Python 当我需要返回值时,exec返回一个nonetype

Python 当我需要返回值时,exec返回一个nonetype,python,python-3.x,exec,Python,Python 3.x,Exec,我早些时候问了一个问题,但遇到了第二个问题 我正在编写一个程序,读取文本文件,并执行文件中的所有代码。这是针对类的,我们必须使用exec() 我在运行代码时遇到了这个错误,无数次的搜索并没有让我找到解决方案 Traceback (most recent call last): File "doxecute.py", line 28, in <module> replace_code(statements, contents) File "doxecute.py", l

我早些时候问了一个问题,但遇到了第二个问题

我正在编写一个程序,读取文本文件,并执行文件中的所有代码。这是针对类的,我们必须使用
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
这是我读到的文件

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]

exec
将始终返回
None
。从:

exec(object[,globals[,locals]])此函数支持动态 Python代码的执行。对象必须是字符串或代码 对象如果它是一个字符串,则该字符串将被解析为Python套件 然后执行的语句(除非出现语法错误)。[1] 如果它是一个代码对象,则只执行它。在所有情况下,代码 所执行的将作为文件输入有效(请参阅第节) 参考手册中的“文件输入”)。请注意,
返回
yield
语句不能在函数定义之外使用 在传递给
exec()
函数的代码上下文中回归 值为
None

这是一个相当奇怪的要求。但您可以像这样捕获输出:

>>> s = """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) %}"""
>>> import re
>>> stmts = re.findall(r'{%\s*\((\w*)\)\s*(.*)%}',s)
>>> stmts
[('c', 'print(x) '), ('d', 'print(2*x) '), ('a', 'import random '), ('b', 'x = random.randint(1,6) ')]
现在,您必须将输出重定向到某个流,以便稍后进行操作:

>>> import io
>>> import sys
>>> stream = io.StringIO()
>>> stdout = sys.stdout # this keeps stdout so we can set it back
>>> sys.stdout = stream
>>> for _, statement in sorted(stmts):
...     exec(statement)
...
>>> sys.stdout = stdout # remember to reset stdout!
现在,您可以获得打印的值:

>>> stream.getvalue()
'5\n10\n'
>>> stream.getvalue().split()
['5', '10']
尽管如此,我认为更简单的方法是将名称空间传递给dict:

>>> namespace = {}
>>> for _, statement in sorted(stmts):
...     exec(statement, namespace)
...
5
10
>>> namespace.keys()
dict_keys(['__builtins__', 'random', 'x'])
除非您自己提供,否则命名空间将加载普通的
\uuuuu内置项。因此,要获得在执行的代码中创建的每个名称,您可以找到
namspace.keys
dictview
和包含字符串
“\uuu内置项”


print()
函数不返回任何内容。这是什么意思?我用它来调试@AshwiniChaudhary
exec
在Python3中总是返回
None
。在Python2中,
exec
是一个语句,因此它实际上不返回任何内容。我得出了这个结论,您知道一种从已执行语句中获取值的方法吗?这是我的教授明确要求的它到底说了什么?你不能,好吧。我走上前去抄袭问题上的内容,意识到我忘了写。我是python新手,所以我不完全理解这个
的含义,您需要在python中使用exec函数。要恢复输出,您需要将输出重定向到您自己的流。您的程序应该接受文件名作为命令行参数,以便在[8]上操作。
@sbowde4好的,我想我知道您想要什么。这是一项非常奇怪的任务。你应该试着理解我在这里做了什么…谢谢你,我正在通读这篇文章并努力理解它。我们与这位教授的所有作业都很奇怪,而且通常都很复杂,即使我们刚刚开始学习这门语言。
>>> namespace = {}
>>> for _, statement in sorted(stmts):
...     exec(statement, namespace)
...
5
10
>>> namespace.keys()
dict_keys(['__builtins__', 'random', 'x'])
>>> namespace.keys()
dict_keys(['__builtins__', 'random', 'x'])
>>> vals = namespace.keys() - {'__builtins__'}
>>> vals
{'random', 'x'}
>>> for val in vals:
...    print(namespace[val])
...
<module 'random' from '/Users/juan/anaconda3/lib/python3.5/random.py'>
5
>>>
>>> import contextlib
>>> stream = io.StringIO()
>>> with contextlib.redirect_stdout(stream):
...     for _, statement in stmts:
...         exec(statement)
...
>>> stream.getvalue()
'5\n10\n'
>>> stream.getvalue().split()
['5', '10']