Posts: 74
Threads: 28
Joined: Feb 2020
Hi
I am looking for the code to return the line number of the call, so I could code
print(line_number())
Arbiel
using Ubuntu 18.04.4 LTS, Python 3.8
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)
Posts: 4,786
Threads: 76
Joined: Jan 2018
Use my printat() function
def printat(*args, **kwargs):
"""Print function with additional line number and filename information.
Adds a string such as "at line 31 in foo.py" to the printed output,
to indicate the position where the printat() function was called.
All the calls to print() in a program can be changed
to provide additional information by adding
print = printat
at the top of the program.
"""
import os, sys
level = kwargs.pop('level', 0)
frame = sys._getframe(level+1)
try:
lineno, code = frame.f_lineno, frame.f_code
args += (f'at line {lineno} in {os.path.basename(code.co_filename)}',)
finally:
del frame
print(*args, **kwargs)
« We can solve any problem by introducing an extra level of indirection »
Posts: 74
Threads: 28
Joined: Feb 2020
Hi Gribouillis
Thank you
It works fine.
Arbiel
using Ubuntu 18.04.4 LTS, Python 3.8
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)
Posts: 74
Threads: 28
Joined: Feb 2020
Hi Gribouillis
Maybe, you should add a piece of advice, to not include the printat fonction in the program, but to record it apart and import it ; else the "print(*args, **kwargs)" at line 24 generates an endless recursive call to printat.
using Ubuntu 18.04.4 LTS, Python 3.8
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)
Posts: 4,786
Threads: 76
Joined: Jan 2018
(Jun-28-2024, 06:48 PM)arbiel Wrote: "print(*args, **kwargs)" at line 24 generates an endless recursive call to printat.
Yes this happens if you write
print = printat
in the file where the printat function is defined. You can avoid recursion by writing
from builtins import print as _print
def printat(...)
....
_print(*args, **kwargs) # note the _print instead of print
Now if you add print = printat somewhere in the file, it won't generate a recursion.
« We can solve any problem by introducing an extra level of indirection »
Posts: 74
Threads: 28
Joined: Feb 2020
Hi
Regarding the line number, I made the error to get it from the file I recorded and in which I inserted two lines in front of gribouillis' function.
Having recorded the file with the name 'ap_gbr_printat.py', I did the following :
import ap_gbr_printat as prt
print = prt.printat
using Ubuntu 18.04.4 LTS, Python 3.8
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)