9

In windows, I am running a bat script that currently ends with a 'pause' and prompts for the user to 'Press any key to continue...'

I am unable to edit the file in this scenario and I need the script to terminate instead of hang waiting for input that will never come. Is there a way I can run this that will disable or circumvent the prompt?

I have tried piping in input and it does not seem to help. This script is being run from python via subprocess.Popen.

Dillon
  • 167
  • 1
  • 8
  • I believe that `pause` is a command that is built-in to the `cmd` interpreter, so it will be impossible to replace it. Otherwise you could just create a `pause.exe` and place it at the front of the path. – Mark Ransom Jul 30 '12 at 21:09
  • I don't understand why piping the input doesn't work, you can redirect from the command line: `pause – Mark Ransom Jul 30 '12 at 21:12

4 Answers4

18

Try to execute cmd.exe /c YourCmdFile < nul

YourCmdFile - full path to your batch script

Maximus
  • 10,751
  • 8
  • 47
  • 65
5
subprocess.call("mybat.bat", stdin=subprocess.DEVNULL)

Would call mybat.bat and redirect input from nul on windows (which disables pause as shown in other answers)

Bryce Guinta
  • 3,456
  • 1
  • 35
  • 36
  • 1
    Note that only works in Python 3. In Python 2.x you have to get a file handle to devnull (e.g. `devnull = open(os.devnull,'r')`) and pass that as stdin instead. – Brent Writes Code Feb 29 '16 at 21:07
  • @BrentNash good catch. I ended up using yours for Python2/3 compatibility. Make sure to close the file after you're done to avoid resource leaks(which Python 3 raises a warning for in this case). – Bryce Guinta Jun 13 '16 at 22:50
4

This one turned out to be a bit of a pain. The redirect of nul from Maximus worked great, thanks!

As for getting that to work in python, it came down to the following. I started with:

BINARY = "C:/Program Files/foo/bar.exe"
subprocess.call([BINARY])

Tried to add the redirection but subprocess.call escapes everything too well and we loose the redirect.

subprocess.call([BINARY + " < nul"])
subprocess.call([BINARY, " < nul"])
subprocess.call([BINARY, "<", "nul"])

Using shell=True didn't work because the space in BINARY made it choke trying to find the executable.

subprocess.call([BINARY + " < nul"], shell=True)

In the end, I had to resort back to os.system and escape myself to get the redirection.

os.system(quote(BINARY) + " < nul")

Not ideal, but it gets the job done.

If anyone knows how to get the last subprocess example to work with the space in the binary, it would be much apprecated!

Druid
  • 6,423
  • 4
  • 41
  • 56
Dillon
  • 167
  • 1
  • 8
0

For me the following code works:

p = Popen("c:\script.bat <nul", cwd="c:\")
darq
  • 1