2

I would like my python program to raise an error:

import os

if not os.path.isdir(args.sample_dir):
    raise OSError('Samples not found.')

When running the code, I receive the following error when the above requirement is met:

Traceback (most recent call last):
  File "/Users/blade/utils.py", line 696, in <module>
    main()
  File "/Users/blade/utils.py", line 663, in main
    raise OSError('Samples not found.')
OSError: Samples not found.

I don't like that I see the error sentence twice. Is there a way to hide the earlier one from log?

Blade
  • 984
  • 3
  • 12
  • 34
  • 1
    Does this answer your question? [Hide traceback unless a debug flag is set](https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set) – Ken Y-N Oct 01 '20 at 02:48
  • 1
    Yes, it is difficult to follow! I think [this](https://gist.github.com/maphew/e3a75c147cca98019cd8) is the final answer, from the OP's first comment on the accepted answer. – Ken Y-N Oct 01 '20 at 03:07
  • @KenY-N Thanks, a difference (correct me if I'm wrong) is that when I use sys.tracebacklimit = 0 it will limit all my error outputs to that one line, whereas I'm just intending to apply it for the error that I specifically raised an error. I'll check the link to make sure I'm not wrong – Blade Oct 01 '20 at 03:11
  • @KenY-N Actually, I think this is right, I should just put sys.tracebacklimit = 0 inside my if statement, that way it only applies to that particular error! Thanks for your help! – Blade Oct 01 '20 at 03:14
  • On `ipython3`, `sys.tracebacklimit = 0` dumped out a huge wall of text for me... – Ken Y-N Oct 01 '20 at 03:38

1 Answers1

-2

I suggest you can use try/except for ignoring one of the error. try: os.path.isdir(args.sample_dir) except
raise OSError('Samples not found.')

  • 2
    This is not good advice. OP wants to check if the value returned by `os.path.isdir()` is `True` or `False`, not if the call itself raises an exception. Also, it's almost always a bad decision to use an unqualified `except` (i can think of one case where it's ok, and this ain't it). – Z4-tier Oct 01 '20 at 03:55