[Tutor] Running Command Prompt In Python
Mats Wichmann
mats at wichmann.us
Thu Feb 29 10:17:23 EST 2024
On 2/29/24 04:26, Am Ra wrote:
> Hi,
> I am trying to activate and run command prompt in python but I am stuck in
> one section of the code. Below I will explain what I have done so far and
> what issue I am dealing with.
>
> Importing os, and using os.system to connect to Command Prompt.
> [image: image.png]
>
> Then, dmel922.exe will be activated to generate an empty csv file from a
> raw dataset.
> [image: image.png]
>
> Up to here it is working as it is supposed to. However, it goes on a pause
> and not adding any data to the empty csv file because it is waiting on the
> user input which is “Enter y to Continue”. As we see in the picture below,
> the Command Prompt is asking the user to press y to continue. As soon as, I
> press y in the Command Prompt it will continue and finish the task.
> [image: image.png]
>
> I just cannot figure out how to write a code in python to answer that
> “Enter y to Continue” prompt or bypass that so that the system continues
> and finishes its task.
>
> Please advise. Thank you very much.
Note: we can't see any of your pictures, the mailing list strips them.
Just paste the text, it's much easier for people to work with anyway.
A lot depends on how the Windows executable (that we know nothing about
beyond what little you've said) is coded. Some programs do cute things
like flush any pending input
before issuing a prompt for a response, which would defeat the below.
If you use subprocess.run to call the program, you have the ability to
connect to the input pipe, so you can send it some text. Whether it will
accept that input in the way you hope we cannot tell. At a conceptual
level, then:
from subprocess import run, PIPE
p = run(command, stdout=PIPE, input="y\n", shell=True, text=True)
# do something with p.stdout, e.g. check that the question was what you
thought
# do something with p.returncode, e.g. check it exited successfully
# shell=True if you really wanted a cmd shell, if you read the subprocess
# docs you'll see that's often not the case.
More information about the Tutor
mailing list