Python ConfigParser cannot search .ini file correctly (Ubuntu 14, Python 3.4)

后端 未结 2 1973
死守一世寂寞
死守一世寂寞 2020-11-28 16:06

Problem: The code compiles fine but when ever i call the read_db_config function i get \"Exception: mysql not found in the mysql_config.ini file\"

The file is in the

2条回答
  •  無奈伤痛
    2020-11-28 17:06

    if you use relative paths for file or directory names python will look for them (or create them) in your current working directory (the $PWD variable in bash).

    if you want to have them relative to the current python file, you can use (python 3.4)

    from pathlib import Path
    HERE = Path(__file__).parent.resolve()
    CONFIG_PATH = HERE / '../etc/mysql_config.ini'
    

    or (python 2.7)

    import os.path
    HERE = os.path.abspath(os.path.dirname(__file__))
    CONFIG_PATH = os.path.join(HERE, '../etc/mysql_config.ini')
    

    if your mysql_config.ini file lives in the etc directory below your python script.

    you could of course always use absolute paths (starting with a /; i.e. /home/someuser/mysql_config.ini).

提交回复
热议问题