使用执行xmgrace批处理子流程.Popen()

2024-06-16 12:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我要用数据从几个文件中画出图形。我已经找到了运行一个简单命令的方法

xmgrace -batch batch.bfile -nosafe -hardcopy

其中批处理文件是一个带有grace命令的文本文件,用于打印我想要的图形。我已经手动试过了,效果很好。要对多个文件执行此操作,我只需在其中编辑一个参数批处理文件每次我做更改时都运行相同的命令。在

我已经写了一个python代码来编辑bfile.batch文件并用for循环遍历所有数据文件。在每个循环步骤中,我想直接在命令行中运行上述命令。在

在搜索了一下之后,我找到了两个解决方案,一个是操作系统()和另一个子流程.Popen()我只能子流程.Popen()在不出错的情况下写作:

^{pr2}$

问题是,这在实践中没有任何作用,也就是说,它与直接在命令行中运行命令不一样。我已经尝试为批处理文件但一切都没有改变。在

我使用的是python2.7和macos10.7


Tags: 文件数据方法命令行命令图形编辑batch
3条回答

使用use 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

您检查过使用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的子流程.Popen('myscript.sh'). 您可以通过运行以下命令来检查在python中为子进程设置了哪些环境变量:

^{pr2}$

相关问题 更多 >