如何解决如何在变量中获取python代码的python交互式shell输出?
假设我有
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。