How to embed python code in batch script

You could use a hybrid technic, this solution works also with an python import.

1>2# : ^
'''
@echo off
echo normal 
echo batch code
echo Switch to python
python "%~f0"
exit /b
rem ^
'''
print "This is Python code"

The batch code is in a multiline string ''' so this is invisible for python.
The batch parser doesn't see the python code, as it exits before.

The first line is the key.
It is valid for batch as also for python!
In python it's only a senseless compare 1>2 without output, the rest of the line is a comment by the #.

For batch 1>2# is a redirection of stream 1 to the file 2#.
The command is a colon : this indicates a label and labeled lines are never printed.
Then the last caret simply append the next line to the label line, so batch doesn't see the ''' line.


Even more efficient, plus it passes all command-line arguments to and returns the exit code from the script:

@SETLOCAL ENABLEDELAYEDEXPANSION & python -x "%~f0" %* & EXIT /B !ERRORLEVEL!
# Your python code goes here...

Here's a break-down of what's happening:

  • @ prevents the script line from being printed
  • SETLOCAL ENABLEDELAYEDEXPANSION allows !ERRORLEVEL! to be evaluated after the python script runs
  • & allows another command to be run on the same line (similar to UNIX's ;)
  • python runs the python interpreter (Must be in %PATH%)
  • -x tells python to ignore the first line (Run python -h for details)
  • "%~f0" expands to the fully-qualified path of the currently executing batch script (Argument %0). It's quoted in case the path contains spaces
  • %* expands all arguments passed to the script, effectively passing them on to the python script
  • EXIT /B tells Windows Batch to exit from the current batch file only (Using just EXIT would cause the calling interpreter to exit)
  • !ERRORLEVEL! expands to the return code from the previous command after it is run. Used as an argument to EXIT /B, it causes the batch script to exit with the return code received from the python interpreter

NOTE: You may have to change "python" to something else if your python binary is not in the PATH or is in a non-standard location. For example:

@"C:\Path\To\Python.exe" -x ...