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

问题描述

假设我有

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代码运行,则可以使用subprocess.Popen函数生成另一个python进程,将stdout,stderr,stdin分别指定为subprocess.PIPE并使用.communicate()函数检索输出。

python使用-c参数来指定您将python代码作为下一个要执行/解释的参数。

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'))
,

您要寻找的功能是内置的python函数

eval(string)