我可以像在交互模式下键入内容一样运行Python文件吗?

2024-04-19 06:52:32 发布

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

例如,我有一个test.py

s='123'
print(s)

我想要这个输出,就像我在python中手动键入它们一样:

>>> s='123'
>>> print(s)
123

但是我想从CLI运行文件。python test.pypython -i test.py不是这样显示的,ipython test.pyipython -i test.py也是这样。你知道吗


Tags: 文件pytest键入cliipython手动print
1条回答
网友
1楼 · 发布于 2024-04-19 06:52:32

将以下内容保存在名为tracer.py的文件中:

import sys

class Tracer(object):
    def __init__(self):
        self._filecache = {'<string>' : open(sys.argv[1], 'r').readlines() or '\n'}
        self._linecache = {'<string>' : 0}

    def accept(self, fn):
        if fn != "<string>": # from exec
            return False
        return True

    def trace(self, frame, event, arg):
        fn = frame.f_code.co_filename
        if not self.accept(fn):
            return self.trace

        if fn not in self._filecache:
          # wait until importing of the module is done to minimize pollution
            f = frame.f_back
            while f is not None:
                try:
                    if 'import' in _filecache[f.f_code.co_filename][f.f_lineno]:
                        return self.trace
                except Exception:
                     pass
                f = f.f_back
            del f

          # import is done, and we're back, accept this file from this point on
            self._filecache[fn] = open(fn, 'r').readlines() or '\n'
            self._linecache[fn] = sys.maxsize

        lno = frame.f_lineno

        ncur = self._linecache[fn]
        buf = self._filecache[fn]

        if event == 'line':
            for i in range(ncur, lno):
                ncur = self._oneline(i, buf)

            self._linecache[fn] = max(ncur, lno)

        elif event == 'return':
            if lno <= ncur:
                fln = frame.f_code.co_firstlineno - 1
                self._oneline(fln, None)
        return self.trace

    def _oneline(self, lineno, buf):
        print('>>> ', end='')

      # simple eol case
        if not buf or not buf[lineno]:
            print()
            return

      # in general, an interpreter "line" may be longer than a file line
        line = buf[lineno].rstrip()
        haseol = False
        while line and (line[-1] in ('(', '\\', ':') or line[0] in (' ', '\t')):
         # this line appears to have a continuation ...
            try:
             # output traced line
                print(line)

             # output continued line
                lineno += 1
                print('... ', end='')
                line = buf[lineno].rstrip()
            except IndexError:
             # shouldn't happen; but must mean that the diagnosis above is
             # wrong and that there is no continuation, keep silent
                break
        else:
            print(line)
            haseol = True

        if not haseol:
            print()

        return lineno

sys.settrace(Tracer().trace)
exec(open(sys.argv[1]).read())
sys.settrace(sys._getframe(0).f_trace)

将要跟踪的代码存储在自己的文件中。例如,您的示例代码,例如test.py

s = '123'
print(s)

并按如下方式运行:

$ python3 tracer.py test.py

产生所需的:

>>> s = '123'
>>> print(s)
123
>>>

我还没在愤怒中测试过,所以可能会有一些小案子。然而,这应该让你开始。你知道吗

相关问题 更多 >