Python – Use the Python child process module to run batch files with more than 10 parameters

Use the Python child process module to run batch files with more than 10 parameters… here is a solution to the problem.

Use the Python child process module to run batch files with more than 10 parameters

I’m 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 before the parameter: “var10” because I don’t know why bat takes the same value for %1 instead of %10, as shown below:

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

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

Thanks!

Solution

Batch files only support %1 through %9. To read the 10th parameter (and the next and next arguments), you must use the command (possibly more times).

shift

Change parameters:

10 parameters to %9, %9 to %8, and so on:

+--------------+----+----+----+----+----+----+----+----+----+----+------+
| 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   |
+--------------+----+----+----+----+----+----+----+----+----+----+------+

( x means that the original %0 is now inaccessible, so if you need it, you must use it before the shift statement.)

).

Now you can use the 10th parameter as %9, the 9th parameter as %8, and so on.

So change your batch file:

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

Related Problems and Solutions