3

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's working fine until the parameter: "var10", because I dont know why the bat is taking the same value for %1, and not for %10, as this:

... >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 the bat it's taking the value for var1 and adding just the 0, but it should be var10.

Thank you!

mtinetti
  • 43
  • 6
  • 1
    Sorry about the previous flag. Wasn't paying attention to the fact this is for windows. Here is a better one: http://stackoverflow.com/q/8328338/3901060 – FamousJameous Apr 19 '17 at 16:32

2 Answers2

2

Batch file supports only %1 to %9. To read 10th parameter (and the next and next one) you have to use the command (maybe more times)

shift

which shifts parameters:

10th parameter to %9, %9 to %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   |
+--------------+----+----+----+----+----+----+----+----+----+----+------+

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

Now you may use the 10th parameter as %9, 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
MarianD
  • 13,096
  • 12
  • 42
  • 54
1

Just to end with this issue, I decided to use only one long parameter because the parameters can be optional and I couldn't find a way to send an empty parameter 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'm 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%" are to discard the ones that comes with the variable %3, remember: "" to escape double-quotes in batch files.

mtinetti
  • 43
  • 6