如何在subprocess.Popen.communicate的输出中找到字符串

时间:2019-07-04 15:23:39

标签: python subprocess

我正在尝试在proc.communicate的输出中为subprocess.Popen找到一个字符串。 我的代码如下:

    proc = subprocess.Popen(["./runCommand.sh" +  " -i " + ip + " -c " + cmd], stdout=subprocess.PIPE, shell=True)
    output = proc.communicate()
    p_status = proc.wait()
    if 'someword' in output:
        #dosomething

似乎我在输出中找不到想要的词。 打印时输出如下所示:

(b'blabla someword\blabla\n', None)

我是否需要进行转换才能找到带有“ in”的东西?


编辑: 到目前为止,感谢您的回答! 我将其更改为“输出[0],但仍然收到错误 TypeError: a bytes-like object is required, not 'str' 我在这里可以做什么?使用解码()?

2 个答案:

答案 0 :(得分:1)

您将获得两个元素元组,如果访问该元组的第一个元素,则可以使用in

>>> 'someword' in (b'blabla someword\blabla\n', None)[0]
True

因此,您需要将output替换为output[0],以使代码正常工作。

答案 1 :(得分:1)

您会将stdout + stderr都放入output中,因此需要检查if 'someword' in output[0]

或更妙的是:

proc = subprocess.Popen(["./runCommand.sh" +  " -i " + ip + " -c " + cmd], stdout=subprocess.PIPE, shell=True)
output, _ = proc.communicate() # or output, err = proc.communicate()
p_status = proc.wait()
if 'someword' in output:
    #dosomething

始终在检查文档

In [7]: subprocess.Popen.communicate?
Signature: subprocess.Popen.communicate(self, input=None)
Docstring:
Interact with process: Send data to stdin.  Read data from
stdout and stderr, until end-of-file is reached.  Wait for
process to terminate.  The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.

communicate() returns a tuple (stdout, stderr).  <<<---
File:      /usr/lib/python2.7/subprocess.py
Type:      instancemethod