Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #196998
| From | dn <PythonList@DancesWithMice.info> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: FileNotFoundError thrown due to file name in file, rather than file itself |
| Date | 2024-11-12 14:10 +1300 |
| Organization | DWM |
| Message-ID | <mailman.95.1731373814.4695.python-list@python.org> (permalink) |
| References | <26418.15836.335097.984240@ixdm.fritz.box> <ZzJ0eoWZds3xSKWn@cskk.homeip.net> <635ef074-15b3-4084-ad34-c350b150a794@DancesWithMice.info> |
On 12/11/24 10:17, Cameron Simpson via Python-list wrote:
> On 11Nov2024 18:24, dieter.maurer@online.de <dieter.maurer@online.de>
> wrote:
>> Loris Bennett wrote at 2024-11-11 15:05 +0100:
>>> I have the following in my program:
>>> try:
>>> logging.config.fileConfig(args.config_file)
>>> config = configparser.ConfigParser()
>>> config.read(args.config_file)
>>> if args.verbose:
>>> print(f"Configuration file: {args.config_file}")
>>> except FileNotFoundError:
>>> print(f"Error: configuration file {args.config_file} not
>>> found. Exiting.")
>>
> My questions are:
>
> 1. Should I be surprised by this behaviour?
No. Python has behaved as-programmed.
>>> 2. In terms of generating a helpful error message, how should one
>>> distinguish between the config file not existing and the log file not
>>> existing?
>
> Generally you should put a try/except around the smallest possible piece
> of code. So:
>
> config = configparser.ConfigParser()
> try:
> config.read(args.config_file)
> except FileNotFoundError as e:
> print(f"Error: configuration file {args.config_file} not found:
> {e}")
>
> This way you know that the config file was missing.
Augmenting @Cameron's excellent advice: please research "Separation of
Concerns", eg https://en.wikipedia.org/wiki/Separation_of_concerns
(which overlaps with one interpretation of SOLID's "Single
Responsibility Principle" and the *nix philosophy of "do one thing, and
do it well").
If you were to explain the code-snippet in English (or ...) it has
several parts/concerns:
- configure the log
- instantiate ConfigParser()
- read the env.file
- advise verbosity-setting
- handle file-error
- (and, but not appearing) terminate execution
A block of code (see indentation for rough definition of "block") should
achieve one thing ("concern"). Thus, the advice to separate-out the
file-read and attendant defensive-coding.
This anticipates the problem (2) of distinguishing the subject of any
one error/stack-trace from any others - and, arguably, makes the code
easier to read.
--
Regards,
=dn
Back to comp.lang.python | Previous | Next | Find similar
Re: FileNotFoundError thrown due to file name in file, rather than file itself dn <PythonList@DancesWithMice.info> - 2024-11-12 14:10 +1300
csiph-web