2

A simple code to read a config file with ConfigParser works fine when it's run on command-line, but the same .py code cannot read the same config file when using VS code.

I've changed the default venv for VScode to make sure to use the same environment with the command-line, but it doesn't work.

import configparser

cfg = configparser.ConfigParser()
cfg.read('setting.conf')
print(cfg.has_section('section1'))

Whereas running the code above returns True, running this on VScode returns following error:

configparser.NoSectionError: No section: 'section1'
martineau
  • 119,623
  • 25
  • 170
  • 301
pomme
  • 97
  • 1
  • 3
  • 11
  • 1
    Are you reading the same 'setting.conf' in both cases? Maybe you should use absolute paths. – Thierry Lathuille Sep 06 '19 at 06:28
  • 4
    It may silently ignoring the fact that the `setting.conf` file wasn't found (see the [documentation](https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read)). You could try changing it to `cfg.read_file(open('setting.conf'))` to determine if that's what the problem is. – martineau Sep 06 '19 at 07:43
  • @martineau That was exactly my problem.. no error, no warning? Come on... – smcs Sep 10 '20 at 12:05
  • 1
    @smcs: Agree about it being a questionable design-choice, but it _is_ documented (along with a description of the proper way to things) — so, as is often the case, reading the fine documentation can actually be a save time overall… – martineau Sep 10 '20 at 12:18
  • @martineau Eternal truth.. I will try to keep it in mind when trying to take shortcuts learning from condensed tutorials and outdated SO answers.. which will probably be in half an hour.. :) Meanwhile I solved the problem by specifying a relative path to the config file as explained [here](https://stackoverflow.com/a/13800583/5522601): `config.read_file(open(os.path.join(os.path.dirname(__file__),"config.ini")))` – smcs Sep 10 '20 at 13:09

0 Answers0