I have a Django project and I have created a formatting script that runs Black and iSort. It appears as the following,
@echo off
:: This line prevents the display of each command before execution.
echo Running isort...
python -m isort .
echo:
echo Running black...
python -m black .
echo:
echo Formatting completed successfully.
It is called format_code.cmd
.
I am trying to get this to run on save. So I created a File Watcher to run the script when a save occurs. The problem is that the python in my virtual environment is what has the developer dependencies which are installed by the developer in a dev_requirements.txt
This means the Python in the venv has everything required, but when the script is ran the formatting file uses a different Python in the OS Path, which does not have the dependencies.
How can I make the File Watcher that runs a CMD formatting script use the Python in the virtual environment so that the developer dependencies can be found?
Answer
You’ve built a sharp tool—a script to enforce code quality—but you're running it in the wrong workshop. When your File Watcher executes format_code.cmd
, it calls out to the generic Python interpreter living on your OS Path. That Python has never seen your project's dev_requirements.txt
. It's a stranger to isort
and black
. This is why it fails.
The amateur blames the tool. The professional commands the environment.
The fix is not a more complex script, but a more intelligent one. You need to tell your script to step inside the right world before it does any work. This is achieved with one foundational command.
Before you call python
, you must first call your virtual environment:
Code snippet