使用subprocess.Popen()执行xmgrace批处理

1 投票
3 回答
1033 浏览
提问于 2025-04-16 22:15

我需要从几个数据文件中制作图表。我已经找到了一种方法,可以运行一个简单的命令

xmgrace -batch batch.bfile -nosafe -hardcopy

其中,batch.bfile是一个文本文件,里面有我想要的图表的指令。我已经手动尝试过这个方法,效果很好。为了处理多个文件,我只需要在batch.bfile中编辑一个参数,然后每次修改后都运行相同的命令。

我已经写了一个Python代码,它会编辑batch.bfile,并通过一个循环遍历所有的数据文件。在每次循环中,我想直接在命令行中运行前面提到的命令。

经过一番搜索,我找到了两种解决方案,一种是使用os.system(),另一种是使用subprocess.Popen(),我只成功让subprocess.Popen()工作,没有出现任何错误,代码如下:

subprocess.Popen("xmgrace -batch batch.bfile -nosafe -hardcopy", shell=True)

问题是,这样做实际上没有任何效果,也就是说,它和直接在命令行中运行命令是不一样的。我已经尝试过为batch.bfile写上完整的目录,但没有任何改变。

我使用的是Python 2.7和Mac OS 10.7

3 个回答

0

当你使用 Popen 的时候,你可以把应用程序的输出捕捉到标准输出(stdout)和标准错误(stderr),然后在你的应用程序中打印出来。这样你就能看到发生了什么事情:

from subprocess import Popen, PIPE
ps = Popen(reportParameters,bufsize=512, stdout = PIPE, stderr = PIPE)
if ps:
   while 1:
      stdout = ps.stdout.readline()
      stderr = ps.stderr.readline()
      exitcode = ps.poll()
      if (not stdout and not stderr) and (exitcode is not None):
         break
      if stdout:
         stdout = stdout[:-1]
         print stdout
      if stderr:
         stderr = stderr[:-1]
         print stderr
0

你可以看看这个链接:http://sourceforge.net/projects/graceplot/

0

你有没有试过在命令行里用sh来运行xmgrace?也就是说,先打开/bin/sh,然后再运行xmgrace……这样做应该和你在设置shell=true时,Popen使用的shell是一样的。

另外一个解决办法是创建一个shell脚本(你可以新建一个文件,比如叫myscript.sh,然后在终端里运行chmod +x命令来给这个文件加上执行权限)。在这个脚本里调用xmgrace:

#!/bin/bash
xmgrace -batch batch.bfile -nosafe -hardcopy

然后你可以测试一下myscript.sh是否能正常工作,这样可以获取到你个人配置文件中的环境变量,这些变量可能和python中的不同。如果这个方法有效,你就可以通过python的subprocess.Popen('myscript.sh')来调用这个脚本。你可以通过运行以下命令来查看python中subprocess设置的环境变量:

import os
os.environ

撰写回答