Similar to npocmaka's solution, if you are having more than one line of batch code in your batch file besides the python code, check this out: http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your-batch-file-script/
@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof
"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])
What this code does is it runs itself as a python file by putting all the batch code into a multiline string. The beginning of this string is in a variable called rem, to make the batch code read it as a comment. The first line containing @echo off
is ignored in the python code because of the -x
parameter.
it is important to mention that if you want to use \
in your batch code, for example in a file path, you'll have to use r"""..."""
to surround it to use it as a raw string without escape sequences.
@echo off
rem = r"""
...
"""