1

This is rather a unusual use case where I had to make a legacy system to work.

I have Windows batch script like following named 'batch_test.bat' (example only):

@echo OFF
set /P choice=Enter your choice: 

if /I "%choice%" == "N" (
    echo "Don't proceed"
)

if /I "%choice%" == "Y" (
    echo "Proceed"
)
if /I "%choice%" == "C" (
    echo "Cancel"

)
EXIT /B 0

I have following python code (sample):

import os

os.system('batch_test.bat')

Question is how do I feed the choice batch script is expecting from Python? I did some look up but could not find the appropriate answer.

thanks.

3
  • If you read the docs for os.system: "The subprocess module provides more powerful facilities… using that module is preferable to using this function…" If you want to control the stdin of a program, or capture its stdout, or run it safely without using the shell, or anything else, use subprocess, not os.system. Commented Aug 1, 2018 at 0:56
  • And notice that the docs linked to from that paragraph, Replacing Older Functions with the subprocess Module, include examples that feed input into other programs, exactly what you haven't been able to find. Commented Aug 1, 2018 at 0:56
  • Note that echo "some text" includes the quotes in the output... Commented Aug 1, 2018 at 8:58

1 Answer 1

1

You can use subprocess.Popen to provide input to a process:

from subprocess import Popen, PIPE
p = Popen('batch_test.bat', stdin=PIPE, stdout=PIPE)
output, _ = p.communicate(b'Y\n')
Sign up to request clarification or add additional context in comments.

1 Comment

This worked! Deep within I found some doc that explains it in subtle way: docs.python.org/3/library/subprocess.html#subprocess.Popen

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.