0

I want to print in the stack trace the value of a variable.

Indeed, when executing my program, I have an error and I would like to know the value of a variable.

I don't have access to the console.


code:

os.chdir(directoryName)

Error:

os.chdir(directoryName) FileNotFoundError: [Errno 2] No such file or directory: '' »

2
  • 1
    can you share your code and the error..! Commented Jan 31, 2023 at 6:22
  • 1
    Brilliant question, can't get why no-one has asked it before! Commented Jan 31, 2023 at 6:43

2 Answers 2

1
  1. You could try to declare a custom exception for debugging value.
class DebuggingValueError(Exception):
    """Exception raised for debugging value.

    Attributes:
        value -- input value which caused the error
        message -- explanation of the error
    """

    def __init__(self, value, message="this value is for debugging"):
        self.value= value
        self.message = message
        super().__init__(self.message)
  1. try to catch this exception in the outside of program.
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
try:
    os.chdir(directoryName)
    ....
    ....
    ....
except Exception as ex:
  logging.exception(ex)
  logging.debug(directoryName)
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this: ``` try: os.chdir("coucou") except Exception as ex: #logging.exception(ex) logging.debug("AZERTYUIOKJHGFD")#directoryName) ``` but "AZERTYUIOKJHGFD" is not printed.
@Colas you might have to config logging to output into stdout in your terminal.
Unfortunately, it still does not work.
0

Two options:

NOTE! Be careful of inadvertently logging PII/sensitive data!

  1. https://github.com/andy-landy/traceback_with_variables also looks excellent! Following on,
from traceback_with_variables import prints_exc


@prints_exc
def f(n):
    print(1 / n)


def main():
    f(0)


main()
  1. Another option is given here - https://stackoverflow.com/a/26178112/1021819

Copying from there (thanks CadentOrange!),

import sys, traceback, logging

logging.basicConfig(level=logging.ERROR)

try: 
    x = 0 
    y = 1 
    z = y / x 
    z = z + 1 
    print "z=%d" % (z) 
except: 
    logging.exception("Values at Exception: x=%d y=%d " % (x,y))

i.e. logging.exception() gives access to the variables defined within the try block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.