Using Python subprocess module to run a batch file with more than 10 parameters

I am using this code:

test.py:

cmd_line = str('C:\mybat.bat') + " "+str('C:\')+" "+str('S:\Test\myexe.exe')+" "+str('var4')+" "+str('var5')+" "+str('var6')+" "+str('var7')+ " "+str('var8') + " "+str('var9')+ " "+ str('var10')

process =  subprocess.Popen(cmd_line, stdin=PIPE, stderr=None, stdout=None, shell=True)
process.communicate()
retcode = process.returncode

      

mybat.bat:

cd /d %1 
%2 %3 %4 %5 %6 %7 %8 %9 %10

      

It works fine up to parameter: "var10" because I don't know why the bat takes the same value for% 1 and not% 10, since this is:

... >cd /d C:\ 
C:\> S:\Test\myexe.exe var4 var5 var6 var7 var8 var9 C:\0

      

I want to read for the last parameter var10, not C: \ 0 because bat takes a value for var1 and only adds 0, but it should be var10.

Thank!

+3


source to share


2 answers


Batch file only supports %1

up to %9

. To read the 10th parameter (and the next and the next), you must use the command (maybe more times)

shift

      

which shifts the parameters:

10th

before %9

, %9

before %8

, etc .:

+--------------+----+----+----+----+----+----+----+----+----+----+------+
| Before shift | %0 | %1 | %2 | %3 | %4 | %5 | %6 | %7 | %8 | %9 | 10th |
+--------------+----+----+----+----+----+----+----+----+----+----+------+
| After shift  | x  | %0 | %1 | %2 | %3 | %4 | %5 | %6 | %7 | %8 | %9   |
+--------------+----+----+----+----+----+----+----+----+----+----+------+

      



(The x means the original %0

is no longer available, so if you need it, you must use it before the operator shift

.)

Now you can use parameter 10th

like %9

, 9th parameter like% 8, etc.

So, change your batch file:

cd /d %1
shift 
%1 %2 %3 %4 %5 %6 %7 %8 %9

      

+2


source


To end this problem, I decided to only use one long parameter because the parameters might be optional and I couldn't find a way to send an empty bit to the bat. The shift command works, but if you have a fixed number of parameters, in my case the number of parameters can be 6, 8, 12, can vary, sooo, the code I am using now:

test.py

main_cmd_line = [ 'C:\mybat.bat' , 'C:\' , 'S:\Test\myexe.exe' ]
variables = var1 + ' ' + var2 + ' ' + var3
parameters_cmd_line = shlex.split( "'" + variables.strip() + "'")

cmd_line = main_cmd_line + parameters_cmd_line

process =  subprocess.Popen(cmd_line, stdin=PIPE, stderr=None, stdout=None, shell=True)
process.communicate()
retcode = process.returncode

      



mybat.bat

set go_to_path=%1
set exe_file=%2
set parameters=%3

cd /d %go_to_path%
%exe_file% "%parameters%"

      

The quotes in "% parameters%" should strip those supplied with the% 3 variable, remember "" to avoid double quotes in batch files.

+1


source







All Articles