Home > Blockchain >  How to close command window after batch script completion
How to close command window after batch script completion

Time:10-23

I have created a batch script to run my python script which needs to be run in a virtual environment. I have added 'exit' to the end of my batch scrip but the command window stays open. My script is below:

@echo off
cmd /k "C:\Users\user\Documents\venv\Scripts\activate & C:\Users\user\Document\forward_test.py"
exit

I think it has something to do with how I am activating the environment but I am not very experienced with batch script. Does anyone know what's going on here?

CodePudding user response:

From the output of cmd /?:

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains

Because of the /k in your command, the new window is opening, running your environment and python scripts, and then staying open. If you change the /k to /c, the window will close once the python script has terminated.

CodePudding user response:

You are already running in cmd.exe, because you've invoked a batch file. Therefore all you need is to activate your environment and run your python script:

@Call "%UserProfile%\Documents\venv\Scripts\activate.bat"
@"P:\ath\To\python.exe" "%UserProfile%\Document\forward_test.py"

Please note, that you will need to insert the correct location for your python.exe, (or py.exe if you have and prefer it), I used your provided paths for acivate and forward_test, please make sure that you use the correct ones, (as it looks like you may have submitted code with one or more typos).

Additionally, if the python script runs something in the background, (doesn't output to the console and takes a while), you may wish to change your second line to:

@Start "" "P:\ath\To\python.exe" "%UserProfile%\Document\forward_test.py"
  • Related