from inspect import currentframe, getframeinfo
cf = currentframe()
filename = getframeinfo(cf).filename
print "This is line 5, python says line ", cf.f_lineno
print "The filename is ", filename
调用为您完成这项工作的函数:
from inspect import currentframe
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
print "This is line 7, python says line ", get_linenumber()
import inspect
file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]
#Try printing inspect.stack() you can see current stack and pick whatever you want
import linecache as allLines
## have in mind that fileName in linecache behaves as any other open statement, you will need a path to a file if file is not in the same directory as script
linesList = allLines.updatechache( fileName ,None)
for i,x in enumerate(lineslist): print(i,x) #prints the line number and content
#or for more info
print(line.cache)
#or you need a specific line
specLine = allLines.getline(fileName,numbOfLine)
#returns a textual line from that number of line
对于额外的信息,对于错误处理,您可以简单地使用
from sys import exc_info
try:
raise YourError # or some other error
except Exception:
print(exc_info() )
import inspect
import sys
import atexit
ERR_FILE = open('errors.log', 'w+', encoding='utf-8')
LOG_FILE = open('log.log', 'w+', encoding='utf-8')
def exit_handler():
# ctrl + C works as well
log("Exiting")
ERR_FILE.close()
LOG_FILE.close()
# close files before exit
atexit.register(exit_handler)
def log(*args, files=[sys.stdout, LOG_FILE]):
# can also add timestamps etc.
cf = inspect.currentframe()
for f in files:
print("DEBUG", f"{inspect.stack()[1][1]}:{cf.f_back.f_lineno}", *args, file=f)
f.flush()
def log_err(*args, files=[ERR_FILE, sys.stderr]):
cf = inspect.currentframe()
for f in files:
print("ERROR", f"{inspect.stack()[1][1]}:{cf.f_back.f_lineno}", *args, file=f)
f.flush()
log("Hello World!")
log_err("error")
from inspect import currentframe, getframeinfo
def HERE(do_print=True):
''' Get the current file and line number in Python script. The line
number is taken from the caller, i.e. where this function is called.
Parameters
----------
do_print : boolean
If True, print the file name and line number to stdout.
Returns
-------
String with file name and line number if do_print is False.
Examples
--------
>>> HERE() # Prints to stdout
>>> print(HERE(do_print=False))
'''
frameinfo = getframeinfo(currentframe().f_back)
filename = frameinfo.filename.split('/')[-1]
linenumber = frameinfo.lineno
loc_str = 'File: %s, line: %d' % (filename, linenumber)
if do_print:
print('HERE AT %s' % (loc_str))
else:
return loc_str
用法:
HERE() # Prints to stdout
# Output: HERE AT File: model.py, line: 275
print(HERE(False)) # Retrieves string and prints it.
# Output: File: model.py, line: 276