keuj6
keuj6

Reputation: 143

Use of pre-commit with PyCharm

I am trying to launch my pre-commit hooks from "commit" button in PyCharm (v. 2020.2). I use a conda venv (created with conda create -n py38 python=3.8) where I installed modules with pip install.

My .pre-commit-config.yaml reads:

repos:
- repo: local
  hooks:
  - id: black
    name: black
    language: system
    entry: black --check
    types: [python]

  - id: isort
    name: isort
    language: system
    entry: isort --check-only
    types: [python]

I use local repo here because I will push my code to an intranet repository not connected to the internet.

Running pre-commit run --all-files runs fine from the command line on my local machine. But when I try to commit from PyCharm (enter image description here), it raises the following error:

Traceback (most recent call last):
  File "c:\bib\envs\py38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None, File "c:\bib\envs\py38\lib\runpy.py", line 86, in _run_code exec(code, run_globals)
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\__main__.py", line 1, in   
    from pre_commit.main import main
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\main.py", line 13, in   
    from pre_commit.commands.autoupdate import autoupdate
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\commands\autoupdate.py", line 14, in   
    from pre_commit.clientlib import InvalidManifestError
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\clientlib.py", line 16, in   
    from pre_commit.error_handler import FatalError
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\error_handler.py", line 10, in   
    from pre_commit.store import Store
  File "c:\bib\envs\py38\lib\site-packages\pre_commit\store.py", line 4, in   
    import sqlite3
  File "c:\bib\envs\py38\lib\sqlite3\__init__.py", line 23, in   
    from sqlite3.dbapi2 import *
  File "c:\bib\envs\py38\lib\sqlite3\dbapi2.py", line 27, in   
    from _sqlite3 import * 
ImportError: DLL load failed while importing _sqlite3: The specified module could not be found.

I think that this bug report on pre-commit's github is of particular relevance. If I understand well, it hints that PyCharm is not actually loading the venv and hence not finding installed packages in this environment. No solution is proposed though.

Anyone has a solution for that?

Upvotes: 13

Views: 18892

Answers (1)

sfeldmann
sfeldmann

Reputation: 357

You have to source the environment for your hooks before executing python.

Create the ENV, but you did that part already.

python3 -m venv path/to/venv

Then create a shell script that sources the env and executes your hook

source path/to/venv/bin/activate
python3 -m path/to/your/python-hook

This way your hook should have the proper env settings. Remember the path from your git hook always start at the repository root.

Upvotes: 0

Related Questions