Running Python Code in Windows Batch File Trick

I found this really neat bit of .bat file magic that will let you save your python script code in a .bat file and run it in windows just like any other script. The nice thing about this is that you don’t have to create a separate “launch.bat” file with one “start python” line in it.

This makes running python scripts in Windows more like it is on a Linux/Mac where you can easily add a #!/usr/bin/env python line to the script and run it directly.

Here’s the bit of tricky batch file magic that does it:

@setlocal enabledelayedexpansion && python -x "%~f0" %* & exit /b !ERRORLEVEL!
#start python code here
print "hello world"

The way it works is that the first line of the file does two different things.

  1. starts python interpreter passing the name of the file in, and the -x option will tell it to skip the first line (containing .bat file code)
  2. When python finishes the script exits.

This nifty trick makes it much nicer for writing admin scripts with python on Windows.

Update: fixed to properly pass command line arguments (%* argument passes through the command line arguments for the bat file to python)