微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在变量中获取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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。