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

2024-04-19 10:42:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在使用字符串的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)

这将在控制台中返回以下内容:

3
[0, 1, 2]
done

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

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

另外,我希望只在python\u字符串执行时获取它的每一行,所以在执行之后,我应该看到下面的每一行

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)

Tags: selfeventstringdefsysresultoneframe
1条回答
网友
1楼 · 发布于 2024-04-19 10:42:29

可以在要运行的程序中作为子进程和管道运行另一个python副本。-参数告诉python从stdin读取程序,并在看到EOF时运行它。你知道吗

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

相关问题 更多 >