Search code examples
pythonbatch-filecmdjupyter-labanaconda3

How to deactivate a conda environment before the batch file exits when closing a jupyter lab instance?


I have a batch file that I use to run my jupyter lab.

file.bat

call <anaconda_dir>\Scripts\activate.bat rasa_ai_conda
jupyter lab
conda deactivate
call conda.bat deactivate

This batch file will activate my rasa virtual environment in anaconda using the windows prompt.

So now when I press ctrl+c for closing my jupyter lab it asks this

Terminate batch job (Y/N)?

First of, the prompt closes even if I enter 'N', how do I fix this.

Secondly, I want all of my script executed before the prompt exits, how do I do this?

Tried searching for fix to this issue but still not able to figure out a solution.


Solution

  • So, I finally found the fix for this. As far as I understood this is what was happening. Correct me if I am wrong.

    So, it turns out that in the batch file jupyter lab is also calling its own batch file. Which replaces the cmd (current process) unlike calling an .exe file which will pause the prompt and run it as a new process. When the jupyter lab instance is closed it basically ends the process, i.e. jupyter lab process which had replaced the cmd process, in turn closing the prompt as it takes that to be the end of the process.

    But when we use call a new process is initialized keeping the original process at pause i.e. cmd prompt paused in the background.

    So, when current running process i.e. jupyter lab is closed, the control is shifted to the previous process i.e. cmd prompt, which will continue to run the next command until the end.

    In the above batch file we just have to make these changes

    call <anaconda_dir>\Scripts\activate.bat rasa_ai_conda
    call jupyter lab
    call conda.bat deactivate
    

    This will run all the commands even after terminating jupyter lab server instance after pressing ctrl+c. So if we enter n for Terminate batch job (Y/N)?, the commands following jupyter lab will run as well.

    This fixes both my issues.

    Please let me know if I understood it correctly. If not please do give the correct explanation for what is happening.