比如我有一个 test.py
文件:
s='123'
print(s)
我希望你能够翻译出以下内容,就像我手动在
python
中输入一样::
>>> s='123'
>>> print(s)
123
但我想从CLI运行这个文件。 python test.py
和 python -i test.py
不会显示出来,同样的,ipython test.py
和 ipython -i test.py
也是如此。
比如我有一个 test.py
文件:
s='123'
print(s)
python
中输入一样::
>>> s='123'
>>> print(s)
123
但我想从CLI运行这个文件。 python test.py
和 python -i test.py
不会显示出来,同样的,ipython test.py
和 ipython -i test.py
也是如此。
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
>>>
我还没有进行过严格的测试,所以可能会有一些特殊情况。不过,这应该能让你开始进展。
trace
模块就是你想要的东西,详情请参阅https://docs.python.org/3/library/trace.html。 - hek2mgl