One line of code to write batch file for Python Script (Modern way).
Batch files are important to schedule job in task scheduler to run Python scripts. We will see in detail sample Python script and the creation of batch file to run that script in different ways starting from traditional to modern way.
Modern way will be generic solution for batch file you can direct run the batch file independent of batch file location or directory.
Please see below steps to understand this in detail:
Step 1: Create sample Python script for testing and place that script in project folder. file name should be “test.py” because we will use same name at the time of batch file creation.
Sample Python script:
Step 2: In this step we will learn to create batch file to run above Python script.
first we will create batch file in traditional way and then we will understand each line mentioned in the batch file. Please see below mention batch script for more details.
d: :: Drive of folder script
cd D:\test :: Change directory to script folder
python test.py :: Run python script with default Python
:: Provide comments in the batch file.
Line 1: I place the folder in d: drive so switch to d: drive first.
Line 2: Second line change the directory of the cmd to project folder. test is my folder in d: drive
Line 3: Third line running the Python script with default Python in the system.
Line 4: Fourth line is used to see the output after running the batch file
Create empty file and paste the above code with you changes related to file path and save the file with name “Automation_batch_V1.bat”. If we change the folder path we will need the change the path in batch file as well to avoid this we will perform modern way which is independent of change file path.
Step 3: In this step we will see modern way to create batch file and we will understand batch script step by step.
cd %~dp0
python test.py
pause
Or
you can write it in one line of code. Please see below code for shortest way to run Python script with batch file.
python %~dp0\test.py%
Lets understand one line of code for batch file. Meaning of each word provided below:
Python: default python to run python script
%~dp0: The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to thebatch file itself.test.py: python script with name test.py
This post is useful for the automation of Python script.
All the code posted on this post will be available on below github link:
If you like this post you can follow me on “https://medium.com/@sscswapnil” and “https://github.com/sscswapnil” for more updates.