简体   繁体   English

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

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

Suppose I have假设我有

code = '2+3'

I want to run this code in python interactive shell and get the output string in a variable.我想在 python 交互式 shell 中运行此代码并在变量中获取输出字符串。 So the result of the execution of code would be stored in another variable called output因此code执行的结果将存储在另一个名为output变量中

In this case, the output variable would be '5'.在这种情况下,输出变量将为“5”。

So is there any way to do this?那么有没有办法做到这一点?

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

!!! !!! note:笔记:

  exec returns None and eval doesn't do my job

Suppose code = "print('hi')" output should be 'hi'假设 code = "print('hi')" 输出应该是 'hi'

Suppose code = 'hi' output should be假设 code = 'hi' 输出应该是

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

if you really must run strings as python code, you COULD spawn another python process with the subprocess.Popen function, specify stdout, stderr, stdin each to subprocess.PIPE and use the .communicate() function to retrieve the output.如果你真的必须运行字符串作为Python代码,你可以产卵与另一个Python程序subprocess.Popen功能时, stdout, stderr, stdin每到subprocess.PIPE和使用.communicate()函数来检索输出。

python takes a -c argument to specify you're giving it python code as the next argument to execute/interpret. python 需要一个 -c 参数来指定你给它 python 代码作为执行/解释的下一个参数。

IE python -c "print(5+5)" will output 10 to stdout IE python -c "print(5+5)"将输出10到 stdout

IE 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM