如何检查选择。选择()是标准输出吗?

2024-06-01 05:11:26 发布

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

proc = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
ready = select.select([proc.stdout, proc.stderr], [], [])[0]
for stream in ready:
    if stream == proc.stdout:
        # do something
    elif stream == proc.stderr:
        # do something else
    else:
        # error

如果我把stdout和stderr都传给选择。选择(),是否有方法在遍历返回的列表时检查并查看正在查看的流?你知道吗


Tags: cmdtruestreamstderrstdoutprocshellselect
1条回答
网友
1楼 · 发布于 2024-06-01 05:11:26

我试着在每个if分支中打印出stream,结果如下:

<_io.BufferedReader name=5>

虽然它说它是一个io.BufferedReader,但它似乎继承了name属性,从^{}-在您的例子中,后者是正确的:

The name can be one of two things:

  • a character string or bytes object representing the path to the file which will be opened. In this case closefd must be True (the default) otherwise an error will be raised.
  • an integer representing the number of an existing OS-level file descriptor to which the resulting FileIO object will give access. When the FileIO object is closed this fd will be closed as well, unless closefd is set to False.

name属性对于相应的流是唯一的,所以我想您可以:

proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

out_stream_name = proc.stdout.name
err_stream_name = proc.stderr.name

ready = select.select([proc.stdout, proc.stderr], [], [])[0]
for stream in ready:
    if stream.name == out_stream_name:
        # looking at stdout
    elif stream.name == err_stream_name:
        # looking at stderr
    else:
        # unknown

希望对你有帮助。你知道吗

相关问题 更多 >