Python sys.stdin和子进程标准输出差异

问题描述 投票:0回答:1

我目前手头有一个较大的问题,所以我首先尝试匹配较小的差异以查看是否可以解决我的问题。

在我的程序中,我使用管道,并通过sys.stdin遍历该输入。我注意到它的类型是<class '_io.TextIOWrapper'>。我试图避免使用管道,而是将代码替换为使用subprocess.run(),并注意到结果改为使用<class 'str'>类型。

这可能是一个非常愚蠢的问题,但我想知道为什么它们不同,并且是否可以使子进程stdout与sys.stdin具有相同的类型。

使用Python 3.7.5

python types subprocess stdout stdin
1个回答
0
投票

您正在比较苹果和桔子。 sys.stdincontentsstr实例(尽管您可以将其配置为返回bytes有点费劲;但是在Python 3.x上,subprocess会返回bytes,除非您指定了text=True或类似名称)将这些字节解码为str)。

Python 3.7.2 (default, Jan 29 2019, 13:41:02) 
[Clang 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> type(sys.stdin)
<class '_io.TextIOWrapper'>
>>> line = sys.stdin.readline()
fnord
>>> type(line)
<class 'str'>
>>> import subprocess
>>> s = subprocess.run(['true'], capture_output=True, text=True)
>>> type(s)
<class 'subprocess.CompletedProcess'>
>>> type(s.stdout)
<class 'str'>

0
投票

[subprocess.run返回一个CompletedProcess实例,并同时捕获所有收集的stdout / stderr。

如果需要流,则需要Popen实例。

© www.soinside.com 2019 - 2024. All rights reserved.