ADM Blog

How to run python code in Windows batch (bat) files

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.

Comments (0) Trackbacks (0)
  1. Holy shit, I wish I found this a week ago. Thank you, this is going to make using psexec to copy/run a python script on a remote machine soooo much easier!

  2. But how do you set it back to ms dos?

Leave a comment

CommentLuv badge


No trackbacks yet.