如何获取变量中 python 代码的 python 交互式 shell 输出?

How to get the python interactive shell output of a python code in a variable?

假设我有

code = '2+3'

我想 运行 这段代码在 python 交互 shell 中获取变量中的输出字符串。 因此 code 的执行结果将存储在另一个名为 output

的变量中

在这种情况下,输出变量将为“5”。

那么有什么办法可以做到这一点吗?

def run_code(string):
    # execute the string
    return output # the string that is given by python interactive shell

!!!注意:

  exec returns None and eval doesn't do my job

假设代码 = "print('hi')" 输出应该是 'hi'

假设代码='hi' 输出应该是

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hi' is not defined 

您要查找的函数是内置的python函数

eval(string)

如果你真的必须 运行 字符串作为 python 代码,你可以使用 subprocess.Popen 函数产生另一个 python 进程,指定每个 stdout, stderr, stdinsubprocess.PIPE 并使用 .communicate() 函数检索输出。

python 采用 -c 参数来指定您将 python 代码作为 execute/interpret.

的下一个参数

IE python -c "print(5+5)" 将输出 10 到标准输出

IE

proc = subprocess.Popen(["python", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print(stdout.decode('utf-8'))