在Windows中使用python 2.7运行外部命令

时间:2015-04-08 15:11:34

标签: python windows python-2.7 path external-process

我是python的初级用户,我在使用命令行开关执行外部命令时遇到问题(在Windows 8 64位中使用python 2.7):

lammpsExe = 'C:/Program Files (x86)/LAMMPS 32-bit 20150403/bin/lmp_serial.exe'
os.system(lammpsExe + " -in in.lmps")

它给出以下错误消息:

  

'C程序'未被识别为内部或外部命令,可操作程序或批处理文件

似乎 os.system 无法理解 lammpsExe 的字符串路径。 然后我尝试 subprocess.call 并在路径中用'\\'替换'/':

lammpsExe = 'C:\\Program Files\\LAMMPS 64-bit 20150330\\bin\\lmp_serial.exe'
subprocess.call([lammpsExe,'-in in.lmps'], shell=True)

但它仍然不起作用,因为命令提示符发出以下警告:

  

IndentationError:意外缩进

我怀疑命令行开关' - '是问题所在。我尝试了',\和/的各种组合,但仍然收到错误消息。

2 个答案:

答案 0 :(得分:0)

subprocess个文档的标题为“替换os.system()

的部分
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)

我建议:

lammpsExe = 'C:\\Program Files\\LAMMPS 64-bit 20150330\\bin\\lmp_serial.exe'
subprocess.call(lammpsExe + ' -in in.lmps', shell=True)

文档确实注意到"通常不需要通过shell调用程序。"

答案 1 :(得分:0)

我想我找到了解决方案。我只需要将路径放在Windows系统变量中,然后直接在脚本中调用命令,而不是尝试在python脚本中为外部命令定义路径:

subprocess.call(['lmp_serial.exe','-in','in.lmps'],shell=True)