Home > OS >  How to create a .bat file which execute python file
How to create a .bat file which execute python file

Time:05-13

I'm new to bat file and started to implementing it. I have a list of linux application commands which starts my application. I have a windows system to deploy, used to git bash to execute those commands, but in every system restart have to start the application manually so I started implementing bat file which mapped in system start up

@echo off

title ML_autostart_API
start "" "C:\Program Files\Git\git-bash.exe"

using the above script I've opened the git bash. In further need to perform below commands

# To activate python Environment
source E:/ML_APIs/Python_Environment/python3.8.10/Scripts/activate 
# To navigate the project dir
cd E:/ML_APIs/API/Call_SessionV1
# To set the environment variables
source config/config.sh
# To run python application
python application.py

have to execute the above using git bash since it is open source commands and doesn't execute in windows. git bash is opening and further commands is not working.

CodePudding user response:

You will need to make 2 files, one for the windows command line (.bat) another for the bash script (.sh). The reason being, after you start the bash console, it will work on different window and it has no idea what your .bat contains. We shall call our scripts as boot.bat and start.sh respectively.

boot.bat

@echo off

title ML_autostart_API
start "C:\Program Files\Git\git-bash.exe" start.sh

Notice the start.sh is added at the end of the start command as parameter.

start.sh

# To activate python Environment
source E:/ML_APIs/Python_Environment/python3.8.10/Scripts/activate 
# To navigate the project dir
cd E:/ML_APIs/API/Call_SessionV1
# To set the environment variables
source config/config.sh
# To run python application
python application.py

Note

  • Both scripts are in the same directory.

  • This answer assumes python is actually recognized in git-bash paths.

    Should this is not the case, you can just use the full path to the executable to call it.

  • A better alternative would be to just execute the bash script directly on start up (using that start "C:\Program Files\Git\git-bash.exe" start.sh), no mixing stuff.

  • Related