问题描述:

I have created a Python script which needs to launch a .bat file based on some condition.

Python script location : \Component\myScript.py

Batch file location : \Component\MS20160825\toExecute.bat

The batch file internally uses some executables which are in \Component\bin\

How do I do following :

  1. Launch .BAT file from Python script so that .BAT executes successfully. BAT file should be able to find executables in \Component\bin\ directory to perform its task and produces desired result.

  2. Hold Python script execution until .BAT finished its execution.

  3. .BAT file has pause >nul statement. I need to bypass it, meaning when .BAT is executed from Python script it should not wait for user to press Enter rather it should terminate normally after executing second last statement. Because the same .BAT file needs to be executed multiple times.

网友答案:

Should solve all problems you are experiencing!

import subprocess

p = subprocess.Popen('batch.bat', shell=True, stdin=subprocess.PIPE)
stdout, stderr = p.communicate()
网友答案:

Thanks to all for their active suggestion.
With small correction following code worked for me:

import subprocess

batchFileLocation = 'Component\\MS20160825'
batchFileFullPath = os.path.join(batchFileLocation, 'toExecute.bat')

p = subprocess.Popen(os.path.abspath(batchFileFullPath), stdin=subprocess.PIPE, cwd = batchFileLocation)
stdout,stderr = p.communicate()

Here cwd argument is very much important, it needs to be updated with the location where batch file is placed then only the batch file will be able to execute correctly.

After that only batch file will be able to search for the binary (placed in a different directory like Component\bin\ in this case) required for its execution.

相关阅读:
Top