【问题标题】:Using Python Subprocess module to run a Batch File with more than 10 parameters使用 Python Subprocess 模块运行超过 10 个参数的批处理文件
【发布时间】:2017-09-16 00:11:41
【问题描述】:

我正在使用此代码:

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。

谢谢!

【问题讨论】:

标签: python subprocess


【解决方案1】:

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

shift

改变参数:

10th参数转%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 语句之前使用它。)

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

所以改变你的批处理文件:

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

【讨论】:

    【解决方案2】:

    为了结束这个问题,我决定只使用一个长参数,因为参数可以是可选的,而且我找不到向 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
    

    mybat.bat

    set go_to_path=%1
    set exe_file=%2
    set parameters=%3
    
    cd /d %go_to_path%
    %exe_file% "%parameters%"
    

    "%parameters%" 中的引号用于丢弃变量 %3 附带的引号,记住:"" 用于转义批处理文件中的双引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-17
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      相关资源
      最近更新 更多