導航:首頁 > 編程語言 > 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列印當前行號相關的資料

熱點內容
Python取ID對應的值 瀏覽:630
現在我的世界什麼伺服器最混亂 瀏覽:762
美國好的源碼出售 瀏覽:323
蘋果ipad文件夾怎麼添加文字 瀏覽:481
騰訊雲連接自己的伺服器地址 瀏覽:216
碩士英語綜合教程pdf 瀏覽:46
分段加密的安全性 瀏覽:507
咪咕直播為什麼沒有適配安卓系統 瀏覽:172
php模版大全 瀏覽:102
沒車能解壓嗎 瀏覽:634
php開發oa系統源碼 瀏覽:759
怎麼安裝蘋果ios的app 瀏覽:581
app拉新如何機刷 瀏覽:480
zendeclipseforphp 瀏覽:480
同時有幾個微信如何加密微信 瀏覽:86
大眾20t壓縮比 瀏覽:566
程序員要記住的500個單詞 瀏覽:831
wq快捷方式在哪個文件夾 瀏覽:965
雲南到河北源碼 瀏覽:92
安卓手機怎麼玩造夢3 瀏覽:60