2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

Use this simple python gui to convert all py scripts in folder to bat files :

0<0# : ^
''' 
@echo off
set script=%~f0
python -x "%script%" %*
exit /b 0/b 0
'''

from tkinter import *
from tkinter import filedialog
import os

def browse_folder():
    foldername = filedialog.askdirectory(initialdir=input_entry.get())
    input_entry.delete(0, END)
    input_entry.insert(0, foldername)

def convert_files():
    input_path = input_entry.get()
    if os.path.isdir(input_path):
        # Input path is a directory, so convert all Python files in the directory
        for filename in os.listdir(input_path):
            if filename.endswith(".py"):
                convert_single_file(os.path.join(input_path, filename))

def convert_single_file(filename):
    if filename:
        with open(filename, 'r') as f:
            content = f.read()
        # Add the batch file code at the beginning of the file
        content = '0<0# : ^\n\'\'\' \n@echo off\nset script=%~f0\npython -x "%script%" %*\nexit /b 0\n\'\'\'\n' + content
        # Get the base name of the original file
        base_name, _ = os.path.splitext(os.path.basename(filename))
        # Save the modified content as a batch file
        with open(os.path.join(os.path.dirname(filename), f"{base_name}.bat"), 'w') as f:
            f.write(content)

root = Tk()
root.title("Python to Batch Converter")

# Scale the GUI by a factor of 4
root.tk.call('tk', 'scaling', 4.0)

input_label = Label(root, text="Input folder:")
input_label.pack()

input_entry = Entry(root)
input_entry.pack()

browse_folder_button = Button(root, text="Browse Folder", command=browse_folder)
browse_folder_button.pack()

convert_button = Button(root, text="CONVERT", command=convert_files)
convert_button.pack()

root.mainloop()

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.