使用子进程的PIPE时如何将python对象<class '_io.TextIOWrapper'>的内容作为字符串获取?

How to get the contents of python object <class '_io.TextIOWrapper'> as a string when using PIPE of subprocess?

我有问题。我的子流程模块吐出一些我不知道如何处理的东西。

在 Arch Linux 上使用 Python 3。

命令包括:​​

尽管我的修订号终端输出为 3,但我似乎无法将此值存储到 Python 变量中。它与我得到一个对象有关,而不是我怀疑该对象的内容。任何帮助将不胜感激。

为了完整起见,我演示了参数 universal_lines 如何影响输出。

鉴于我系统上的 svn 版本是 3:

shell=True, cwd=branch, universal_lines=False

#!/usr/bin/env python
import os
import subprocess

branch = '/home/username/svncheckoutfolder'
command = 'svn info "%s" | grep -IEi "Revision:" | sed -e "s/^Revision: \([0-9]*\)/\1/g"' % (branch) # filters out revision number from svn info command
process = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True,cwd=branch) # cwd=branch is only necessary when command contains LaTeX interpreter. In this case, I included the absolute path within the command.
process_stdout = process.communicate()[0]
current_revision = process.stdout # This should be a revision number.
print (type(current_revision)) # <class '_io.BufferedReader'>
print (current_revision) # <_io.BufferedReader name=3>

结果:

<class '_io.BufferedReader'>
<_io.BufferedReader name=3>

shell=True, cwd=branch, universal_lines=True

#!/usr/bin/env python
import os
import subprocess

branch = '/home/username/svncheckoutfolder'
command = 'svn info "%s" | grep -IEi "Revision:" | sed -e "s/^Revision: \([0-9]*\)/\1/g"' % (branch) # filters out revision number from svn info command
process = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True,cwd=branch) # cwd=branch is only necessary when command contains LaTeX interpreter. In this case, I included the absolute path within the command.
process_stdout = process.communicate()[0]
current_revision = process.stdout # This should be a revision number.
print (type(current_revision)) # <class '_io.TextIOWrapper'>
print (current_revision) # <_io.TextIOWrapper name=3 encoding='UTF-8'>

结果:

<class '_io.TextIOWrapper'>
<_io.TextIOWrapper name=3 encoding='UTF-8'>

我尝试读取该对象,但这也不起作用:

print(current_revision.read())

结果:

ValueError: read of closed file

您没有在此处使用 Popen.communicate() 的 return 值:

current_revision = process.stdout

您正在引用 subprocess 模块用于与 shell 通信的(现已关闭)文件对象。您完全忽略了前一行 returned 的值。

只需使用:

process_stdout = process.communicate()[0]
current_revision = process_stdout.decode('utf8').strip()

不使用时universal_newlines=True,或

process_stdout = process.communicate()[0]
current_revision = process_stdout.strip()

当你这样做的时候。数据包括一个换行符,因此 str.strip() 调用。

如果您只需要命令的标准输出输出,您可以只使用 subprocess.check_output() function

output = subprocess.check_output(
    command, shell=True, cwd=branch, universal_newlines=True)

最后但同样重要的是,让 Python 解析响应可能更简单:

command = ('svn', 'info', branch)
output = subprocess.check_output(command, universal_newlines=True)
revision = None
for line in output.splitlines():
    if line.startswith('Revision:'):
        revision = line.partition(':')[1].strip()
        break