# numberlines.py
import fileinput
for line in fileinput.input('E:\PY\numberlines',inplace=True):
line = line.rstrip()
num = fileinput.lineno()
print '%-40s # %2i' %(line,num)
写好后保存路径在E:\PY\numberlines.py
然后按照书上说执行$ ptython numberlins.py numberlines.py
我在Python自带的Python shell上输入$ ptython numberlins.py numberlines.py
得到的结果如下:SyntaxError: invalid syntax
为啥得不到书上描述的那样的结果呢?求大神指点,如何执行才能得到书本上写的那个结果:
# numberlines.py #1
#2
import fileinput #3
#4
for line in fileinput.input('E:\PY\numberlines',inplace=True): #5
line = line.rstrip() #6
num = fileinput.lineno() #7
print '%-40s # %2i' %(line,num) #8
环境是windows7上的Python 2.7
关于Python中的一段为Python脚本添加行号脚本
答案:1 悬赏:0 手机版
解决时间 2021-02-04 02:11
- 提问者网友:别再叽里呱啦
- 2021-02-03 15:45
最佳答案
- 五星知识达人网友:独行浪子会拥风
- 2021-02-03 16:55
C语言有__LINE__来表示源代码的当前行号,经常在记录日志时使用。Python如何获取源代码的当前行号?
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?
exception输出的函数调用栈就是个典型的应用:
A typical example is the output of function call stack when an exception:
python代码
File "D:\workspace\Python\src\lang\lineno.py", line 19, in
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or modulo by zero
那么我们就从错误栈的输出入手,traceback模块中:
Now that, Let's begin with the output of an exception call stack, in the traceback module:
python代码
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)
def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())
traceback模块构造一个ZeroDivisionError,并通过sys模块的exc_info()来获取运行时上下文。我们看到,所有的秘密都在tb_frame中,这是函数调用栈中的一个帧。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys module to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.
对,就是这么简单!只要我们能找到调用栈frame对象即可获取到行号!因此,我们可以用同样的方法来达到目的,我们自定义一个lineno函数:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:
python代码
import sys
def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno
def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()
是否有更方便的方法获取到frame对象?当然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!
python代码
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno
类似地,通过frame对象,我们还可以获取到当前文件、当前函数等信息,就像C语音的__FILE__与__FUNCTION__一样。其实现方式,留给你们自己去发现。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?
exception输出的函数调用栈就是个典型的应用:
A typical example is the output of function call stack when an exception:
python代码
File "D:\workspace\Python\src\lang\lineno.py", line 19, in
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or modulo by zero
那么我们就从错误栈的输出入手,traceback模块中:
Now that, Let's begin with the output of an exception call stack, in the traceback module:
python代码
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)
def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())
traceback模块构造一个ZeroDivisionError,并通过sys模块的exc_info()来获取运行时上下文。我们看到,所有的秘密都在tb_frame中,这是函数调用栈中的一个帧。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys module to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.
对,就是这么简单!只要我们能找到调用栈frame对象即可获取到行号!因此,我们可以用同样的方法来达到目的,我们自定义一个lineno函数:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:
python代码
import sys
def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno
def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()
是否有更方便的方法获取到frame对象?当然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!
python代码
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno
类似地,通过frame对象,我们还可以获取到当前文件、当前函数等信息,就像C语音的__FILE__与__FUNCTION__一样。其实现方式,留给你们自己去发现。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯