使用Python子流程模块运行包含10个以上参数的批处理文件

使用Python子流程模块运行包含10个以上参数的批处理文件,python,subprocess,Python,Subprocess,我正在使用以下代码: 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_li

我正在使用以下代码:

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
在参数“var10”出现之前,它工作正常,因为我不知道为什么bat对%1采用相同的值,而对%10采用相同的值,如下所示:

... >cd /d C:\ 
C:\> S:\Test\myexe.exe var4 var5 var6 var7 var8 var9 C:\0
我想读取最后一个参数var10,而不是C:\0,因为bat它取var1的值,只加上0,但它应该是var10


谢谢大家!

批处理文件仅支持
%1
%9
。要读取第10个参数(以及下一个和下一个),您必须使用命令(可能更多次)

哪些参数会改变:

10
参数到
%9
%9
%8
,等等:

+--------------+----+----+----+----+----+----+----+----+----+----+------+
| 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表示原始的
%0
现在无法访问,因此如果需要,必须在
shift
语句之前使用。)

现在,您可以将
10
参数用作
%9
,将第9个参数用作%8,依此类推

因此,请更改批处理文件:

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

为了结束这个问题,我决定只使用一个长参数,因为这些参数可以是可选的,而且我找不到向bat发送空参数的方法。shift命令可以工作,但是如果您有固定数量的参数,在我的例子中,参数的数量可以是6、8、12,可以变化,所以,我现在使用的代码是:

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
蝙蝠

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

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

“%parameters%”中的引号将丢弃变量%3随附的引号,请记住:“”将在批处理文件中转义双引号。

对于前面的标志,我感到抱歉。没有注意到这是针对windows的。这里有一个更好的:
set go_to_path=%1
set exe_file=%2
set parameters=%3

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