Python:使用python

时间:2018-05-08 14:34:34

标签: python bash

我有一个名为g2p的bash脚本文件,其运行如下:

$echo "teststring" | ./g2p @g2pumap=./map.txt

现在我正在使用python 2.6编写python脚本,我需要在python中运行这个bash脚本(g2p)。

我检查了这个答案:Python: subprocess and running a bash script with multiple arguments

我写道:

import subprocess

val = subprocess.check_call(["./eng_GBR/g2p",  "./map.txt"],  shell=True) 

我的问题是如何在python代码中向g2p(bash脚本)发送标准输入,而且我对@ g2pumap参数的传递值感到有点困惑。

2 个答案:

答案 0 :(得分:2)

稍后在问题中添加了对Python2.6的限制。便携式解决方案就在这个答案的最后。

自Python 3.5以来,subprocess.run应与大多数“使用X的调用程序”用例匹配。它的input参数符合您的要求:

  

input参数传递给子进程的stdin。

您可以直接为其提供字节字符串:

import subprocess

g2p_process = subprocess.run(["./eng_GBR/g2p",  "@g2pumap=./map.txt"], input=b'teststring\n')

这相当于你的bash调用。请注意,您必须自己添加适当的换行符(最后为b"\n")。任何参数,例如@g2pumap=./map.txt,都可以在不转义的情况下传递。

如果您希望获得check_call的例外情况,请在之后使用g2p_process.check_returncode()

如果您遇到旧版本或需要向后兼容,那么使用裸subprocess.Popen是最便携的。以下应处理您的用例:

import subprocess

g2p_process = subprocess.Popen(
    ["./eng_GBR/g2p", "@g2pumap=./map.txt"],
    stdin=subprocess.PIPE,  # allow sending data via STDIN
)
g2p_process.communicate(input="teststring\n")
if g2p_process.returncode != 0:
    raise RuntimeError

请注意,如果需要,您还可以捕获stdout和stderr。在stdout=subprocess.PIPE的通话中使用stderr=subprocess.PIPE和/或Popen。这样做可以让g2p_process.communicate返回有意义的(stdoutdata, stderrdata)元组。

请参阅subprocess.Popen method docs了解如何使用此类对象。检查returncodekill悬空过程通常是个好主意。如果您愿意,也可以复制subprocess.run,因为它可以正确处理错误。

答案 1 :(得分:0)

class CFDataView {
  constructor(...args) {
    super(...args)
    this.offset = 0;
  }
  readU8() {
    if (this.byteLength >= this.offset+1) {
      return this.getUint8(this.offset++);
    } else {
      return null;
    }
  }
}