获取指令的第n行

2024-03-28 10:37:17 发布

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

我正在写一个代码,我已经知道当我有更多的信息时,我将不得不更改一些指令。 我已经知道我将要更改的具体行,但是由于代码有点长,我想通过打印这些行的n°来准备更改这些行的时刻。实际上,我想要一个类似this_line()函数的函数,它的工作方式如下:

1 
2 
3 print('this line is the n°'.format(this_line())
4

>>> this line is the n°3

我能在不转换.txt格式的代码和计算行数的情况下完成这项工作吗?你知道吗


Tags: the函数代码txt信息formatis格式
1条回答
网友
1楼 · 发布于 2024-03-28 10:37:17

The ^{} module你有保险吗。只需import inspect,然后运行:

inspect.currentframe().f_lineno

获取当前执行帧的行号。你知道吗

注意,这是CPython(参考解释器)特有的特性,参见文档:

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

我不清楚帧的概念和它的行号是否会存在于其他地方,但这在引用解释器上可以很好地工作。有可能这是便携式的(没有其他声明),但我不能确定:

inspect.stack()[0].lineno

相关问题 更多 >