问题描述
假设我有
code = '2+3'
我想在python交互式shell中运行此代码,并在变量中获取输出字符串。
因此,执行code
的结果将存储在另一个名为output
那么有什么办法吗?
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
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)