Search code examples
pythonwindowsbatch-filescripting

Execute multi-line python code inside Windows Batch script


I want to use multiline python statements inside Windows Batch script.

For example, my BAT script is:

@echo off
echo "Executing Python Code..."
goto python_code

:python_code_back
echo "Executed Python Code!"

pause
exit()

:python_code
python -c print("""Python code running""")
goto python_code_back

python -c works fine for single statements. But let my python code be embedded is:

import random
num = input("Enter Number: ")
num = int(num)
if num%2 == 0:
  print("Even")
else:
  print("Odd")
  
exit()

How do I embed this Python code into my Windows Batch Script without calling another python script or making temporary python files?

I have some options that I have gone through:

  1. Use python -c with semicolons: How do I intend the code like if statements above? If there are ways, one might still want clean code in multiple lines but I would appreciate the answer for this.

  2. Can I just run python and find a way to send commands to the interpreter? Maybe using subprocesses?

  3. Is there any way I can build a multi-line string that has the python code and then send it to the python interpreter or python command?

  4. In bash we could use EOF to keep multi-lines clean. Is there any similar method to this in BAT? I think no because people have proposed many workarounds to this.

  5. Can ''' (three single-quotes) or """ (three douuble-quotes) syntax be used that are specially interpreted by Batch? Like here?


Solution

  • Try like this:

    0<0# : ^
    ''' 
    @echo off
    echo batch code
    python %~f0 %* 
    exit /b 0
    '''
    
    import random
    import sys
    
    
    
    def isOdd():
        print("python code")
        num = input("Enter Number: ")
        num = int(num)
        if num%2 == 0:
          print("Even")
        else:
          print("Odd")
    
    def printScriptName():
        print(sys.modules['__main__'].__file__)
        
    eval(sys.argv[1] + '()')
    exit()
    

    Example usage:

    call pythonEmbeddedInBatch.bat isOdd
    call pythonEmbeddedInBatch.bat printScriptName
    

    The first line will be boolean expression in python ,but a redirection to an empty label in batch. The rest of the batch code will be within multiline python comment.