通过python将参数传递到批处理文件中

use*_*858 0 python batch-file

我正在尝试将参数发送到批处理文件。

我有一个批处理文件HelloWorld.bat,它在脚本的各个点上总共需要4个输入。我尝试使用subprocess.Popen,subprocess.call和os.system,但是我无法传递参数。这是到目前为止的内容:

p = subprocess.Popen(shlex.split("cmd"), shell = True, stdin = subprocess.PIPE)
p.communicate(
     "cd " + filepath + "\n" +
     "HelloWorld.bat\n" +

     "arg1\n" +
     "arg2\n" +
     "arg3\n" +
     "arg4\n"
 )
Run Code Online (Sandbox Code Playgroud)

当我运行这段代码时,它说的是错误的命令语法。无论如何,我可以将参数传递给将在cmd中运行的批处理文件吗?

谢谢!

Bur*_*lid 5

您不需要shell=TrueWindows,只需按顺序传递参数即可,如下所示:

executable = os.path.join(filepath, 'HelloWorld.bat')
p = subprocess.Popen([executable, 'arg1', 'arg2', 'arg3', 'arg4'])
Run Code Online (Sandbox Code Playgroud)

子流程模块的文档中有很多信息,我建议您仔细阅读它,因为如果您不小心的话,可以轻松地管理系统。