導航:首頁 > 編程語言 > python列印當前行號

python列印當前行號

發布時間:2022-08-12 09:08:23

python裡面idle怎麼顯示行號

㈡ python按照指定字元串列印出這個字元串的後面幾行中的特定字元串開頭的行。

Python Code:


cfgParser=ConfigParser()
cfgParser.read(r"D:a.txt")#路徑修改為你電腦中的即可
cfgParser.get("test","path")

輸出:'/test1/test'

㈢ 關於Python中的一段為Python腳本添加行號腳本

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 <mole>
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or molo by zero

那麼我們就從錯誤棧的輸出入手,traceback模塊中:
Now that, Let's begin with the output of an exception call stack, in the traceback mole:

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 mole 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.

㈣ python怎麼PRINT出第幾行

a =['a', 'b', 'c']

for i,t in enumerate(a):

print i,t

0 a

1 b

2 c

㈤ python中怎麼列印行號和文件名

通過調用堆棧裡面的代碼對象來獲取。

一般是自己引發一個異常,然後捕獲這個異常,在異常處理中通過堆棧信息獲得行號。

比如:

try:
raiseZeroDivisionError
exceptZeroDivisionError:
frame=sys.exc_info()[2].tb_frame.f_back
returnframe.f_lineno

如果需要更多的信息,可以通過inspect模塊的stack()方法獲得整個調用棧。可自定義一個exception類型。

importinspect
classMyErrorCode(object):
STANDARD=0x0001

code_map_msg={
MyErrorCode.STANDARD:"standarderror",
}
classMyError(Exception):
def__init__(self,error_code):
self.error_code=error_code
try:
_current_call=inspect.stack()[1]
_iframe=_current_call[0]
self.line_no=_iframe.f_lineno
self.mole_name=_iframe.f_globals.get("__name__","")
self.method_name=_current_call[3]
self.class_name=_iframe.f_locals.get("self",None).__class__.__name__
except(IndexError,AttributeError):
self.line_no=""
self.mole_name=""
self.method_name=""
self.class_name=""

def__repr__(self):
msg=code_map_msg.get(self.error_code,"")
return"[*]MyError:%s>%s.mole:%s,class:%s,method:%s,line:%s"%(self.error_code,msg,self.mole_name,self.class_name,self.method_name,self.line_no)

def__str__(self):
returncode_map_msg.get(self.error_code,"notfindanymatchmsgforcode:%s"%self.error_code)

然後在需要獲取行號的地方引發這個異常並捕獲它,然後從異常對象中獲取line_no.

㈥ python如何列印關鍵詞所在行

forlinein______:#逐行掃描
ifccinline:#檢查關鍵詞是否存在
print(line)
break#列印cc出第一次出現的那行文字,結束當前的循環
else:continue

㈦ 知道一個文本中某些行的行號,怎樣用python直接讀出來呢如只想讀出第100行的文本。

1.python中只有seek能跳躍的讀,但是是按照位元組來的,如果你的文本每一行都是一樣的長度的話倒是可以。f.seek(99*n)之後再f.readline()

2.如果不知道每行長度的話,那麼就循環100次readline()吧,這個總比直接readlines()好,如果全部長1萬行,這樣也只讀了100行,readlines()卻要讀10000行。

3.如果文本是自己寫的話,可以事先坐下標記最好了。

㈧ 在idle中如何顯示行號

其實IDLE提供了一個顯示所有行和所有字元的功能。

我們打開IDLE shell或者IDLE編輯器,可以看到左下角有個Ln和Col,事實上,Ln是當前游標所在行,Col是當前游標所在列。

我們如果想得到文件代碼有多少行,我們可以直接移動游標到行末,以此來得到一個行數。

㈨ IDLE(python) 怎麼顯示行數

1、打開IDLE shell或者IDLE編輯器,可以看到左下角有個Ln和Col,事實上,Ln是當前游標所在行,Col是當前游標所在列。我們如果想得到文件代碼有多少行,我們可以直接移動游標到行末,以此來得到一個行數。

㈩ 請教大家,python編程:怎麼為該程序輸出的每行標上行號:

count = 1
for i in range(1,5):
....for j in range(1,5):
........for k in range(1,5):
............if( i != k ) and (i != j) and (j != k):
................print count,':',i,j,k
............count+=1

閱讀全文

與python列印當前行號相關的資料

熱點內容
php個性qq源碼 瀏覽:821
初學c語言顯示源未編譯 瀏覽:245
資產概況源碼 瀏覽:472
dos命令建文件夾命令 瀏覽:379
解壓的密碼htm被屏蔽 瀏覽:502
冬天太冷冰箱壓縮機不啟動怎麼辦 瀏覽:83
手機打開vcf需要什麼編譯器 瀏覽:910
加密磁碟後開機很慢 瀏覽:271
長沙智能雲控系統源碼 瀏覽:258
阿里雲伺服器如何設置操作系統 瀏覽:999
超級命令的英文 瀏覽:784
做賬為什麼要用加密狗 瀏覽:586
考研群體怎麼解壓 瀏覽:159
linux修改命令提示符 瀏覽:226
圓圈裡面k圖標是什麼app 瀏覽:63
pdf加空白頁 瀏覽:948
linux伺服器如何看網卡狀態 瀏覽:318
解壓新奇特視頻 瀏覽:707
圖書信息管理系統java 瀏覽:554
各種直線命令詳解 瀏覽:864