Run a .Bat File Using Python Code

Creating a BAT file for python script

c:\python27\python.exe c:\somescript.py %*

Execute batch file using Python script

Backslash escapes special characters in python. Therefore, the paths that you are creating here are not the ones you think they are:

In [1]: test = "..\bfoo"

In [2]: test
Out[2]: '..\x08foo'

Use raw strings instead:

In [3]: test = r"..\bfoo"

In [4]: test
Out[4]: '..\\bfoo'

And actually, the best way to combine path segments in python is by using os.path.join. This will automatically take care of the backslash vs. slash issues for Unix-lie vs. Windows operating systems.

How to run batch file using python script?

You can use os.system:

import os
os.system('Path to your .bat file')

How to execute program or batch file?

Cat is a binary included in Unix systems, since windows isn't based on Unix, it wouldn't work. You should rather try the TYPE command in Windows

How to create a .bat file which execute python file

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.

How do I execute a .BAT script before debugging Python code?

I solved the problem by :

  1. Execute the CMD command.
  2. Execute the BAT script in the window.
  3. Execution of the PyCharm64.exe Program (mine is :C:\Program Files\JetBrains\PyCharm 2021.1.2\bin\ PyCharm64.exe)

In this case, the PyCharm program is a child of CMD.



Related Topics



Leave a reply



Submit