Python Forum
Printing the code line number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing the code line number
#1
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)
Reply
#2
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 »
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 448 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  Sequential number for rows retrieved and storing the Primary UKey to the line number GYKR 2 710 Aug-22-2023, 10:14 AM
Last Post: GYKR
  help me simple code result min and max number abrahimusmaximus 2 1,040 Nov-12-2022, 07:52 AM
Last Post: buran
  how long can a line of code be? Skaperen 2 2,327 Jun-09-2021, 06:31 PM
Last Post: Skaperen
  Even number code syntax error MrCeez 1 2,373 May-02-2021, 06:43 PM
Last Post: Larz60+
  Printing a specific line from a JSON serpiente 4 4,091 Mar-14-2021, 07:27 PM
Last Post: buran
  I need a code line to spam a keyboard key | Image detection bot Aizou 2 3,291 Dec-06-2020, 10:10 PM
Last Post: Aizou
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,357 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  Line of code to show dictionary doesn't work MaartenRo 2 2,555 Jul-28-2020, 03:58 PM
Last Post: deanhystad
  Monitor specific line of code from website Olimpiarob 1 1,944 Jul-09-2020, 03:20 PM
Last Post: mrdominikku

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020