''将输出从通信拆分''

2024-05-19 10:29:09 发布

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

我尝试使用communicate从名为clasp的程序中获取字符串输出,但当我尝试使用split python时,它告诉我:

AttributeError: 'tuple' object has no attribute 'split'

当我尝试用.join Python将元组转换为字符串时,会说:

TypeError: sequence item 0: expected str instance, bytes found

所以我不明白使用communicate的输出类型,我读了那么多帖子,但都没用。输出是字节对象?还是元组?你知道吗

def resolve(self):
    p = Popen(['clasp', 'propositions.txt'], stdout=PIPE)#stdin=PIPE, stdout=PIPE, stderr=PIPE 
    output= p.communicate("input data that is passed to subprocess' stdin")

    print (output)

    str = '/n'.join(output)
    print (output.split("c Answer: 1",1)[1])

Tags: 字符串程序outputstdinstdoutsplit元组attributeerror
2条回答

第一个communicate返回tuple:输出和错误数据。执行:

output, _ = p.communicate("input data that is passed to subprocess' stdin")

那么

str = '/n'.join(output)

毫无意义,output是一个包含所有行的缓冲区,就像bytes(无论如何,您都不会使用str

所以你只需要:

print (output.decode().split("c Answer: 1",1)[1])

Python 3.7 docs我们有

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

所以output[0]是stdout中的数据,所以打印时只需print(output[0])

相关问题 更多 >

    热门问题