通过python将参数传递到批处理文件中 [英] Passing arguments into batch file via python

查看:174
本文介绍了通过python将参数传递到批处理文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to send arguments to a batch file.

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

I have a batch file, HelloWorld.bat and it asks for 4 inputs in total at various points in the script. I tried using subprocess.Popen, subprocess.call, and os.system but I haven't been able to pass the arguments in. This is what I've got so far:

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"
 )

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

When I run this code it says that wrong command syntax. Is there anyway I can pass arguments to the batch file that will be running in cmd?

谢谢!

推荐答案

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

You don't need shell=True for Windows, you can simply pass the arguments in a sequence, like this:

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

文档中有很多信息,有关子流程模块,我建议您通读一遍,因为如果不小心,您可以轻松地连接系统.

There is a lot of information at the documentation for the subprocess module, I suggest a good read through it as you can easily hose your system if you are not careful.

这篇关于通过python将参数传递到批处理文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆