如何使用 inspect/subprocess/sys python 包从 python 中的控制台获取文本以及它执行时的每一行?

How to use inspect/subprocess/sys python packages to attain the text from the console in python as well as each line as it executes?

我想在使用字符串的 exec 函数以及脚本中执行它的行时使用 python 从控制台获取文本

我有以下 python 脚本作为字符串,我使用 exec

对其进行评估
python_string = """
result_one = len([1,2,3])
print result_one
result_two = range(r)
print result_two
result_three = max(result_two)
print "done"
"""
exec(python_string)

此 returns 控制台中的以下内容:

3
[0, 1, 2]
done

我想在控制台执行时获取控制台中的文本。换句话说,我想要返回以下三个字符串,因为它们出现在控制台中

'3'
'[0, 1, 2]'
'done'

此外,我只想在执行时获取 python_string 的每一行,所以我应该在执行后看到下面的每一行

result_one = len([1,2,3])
print result_one
result_two = range(r)
print result_two
result_three = max(result_two)
print "done"

我相信要实现这一点,我需要在调用堆栈中获得相关框架,我一直在此处阅读:What is the difference between a stack and a frame?

我试图用下面的代码完成这个但收效甚微:

import sys
import inspect

python_string_as_dictionary = dict(enumerate(open(inspect.getfile(inspect.currentframe()), 'r+').read().split("\n")))
#>>{0: 'import sys', 1: 'import inspect', 2: '', 3: 'f_dict = dict(enumerate(open(inspect.getfile(inspect.currentframe()), \'r+\').read().split("\n")))', 4: 'print f_dict', 5: 'class SetTrace(object):', 6: '    def __init__(self, func):', 7: '        self.func = func', 8: '', 9: '    def __enter__(self):', 10: '        sys.settrace(self.func)', 11: '        return self', 12: '', 13: '    def __exit__(self, ext_type, exc_value, traceback):', 14: '        sys.settrace(None)', 15: '', 16: '', 17: 'def monitor(frame, event, arg):', 18: '\tprint event', 19: '\tprint "line: {}".format(str(frame.f_lineno))', 20: '\tif event == "line" :', 21: '\t\treturn monitor', 22: '', 23: 'python_string = """', 24: 'result_one = len([1,2,3])', 25: 'print result_one', 26: 'result_two = range(result_one)', 27: 'print result_two', 28: 'result_three = max(result_two)', 29: 'print "done"', 30: '"""', 31: 'with SetTrace(monitor):', 32: '    exec(python_string)', 33: '', 34: '', 35: ''}

class SetTrace(object):
    def __init__(self, func):
        self.func = func

    def __enter__(self):
        sys.settrace(self.func)
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        sys.settrace(None)


def monitor(frame, event, arg):
    print "line: {}".format(str(frame.f_lineno))
    print python_string_as_dictionary[frame.f_lineno-1].strip()
    if event == "line" :
        return monitor

python_string = """
result_one = len([1,2,3])
print result_one
result_two = range(result_one)
print result_two
result_three = max(result_two)
print "done"
"""
with SetTrace(monitor):
    exec(python_string)

您可以 运行 python 的另一个副本作为子进程并通过管道输入您想要 运行 的程序。 - 参数告诉 python 在看到 EOF.

时从 stdin 和 运行 读取程序
import subprocess as subp

python_string = """
result_one = len([1,2,3])
print result_one
result_two = range(result_one)
print result_two
result_three = max(result_two)
print result_three
print "done"
"""

proc = subp.Popen(['python', '-'], stdin=subp.PIPE,
    stdout=subp.PIPE, stderr=subp.STDOUT)
proc.stdin.write(python_string)
proc.stdin.close()
for line in proc.stdout:
    print 'out: {}'.format(line.strip())
proc.wait()