python - 在 python 中捕获 ONLY stdout 的输出

标签 python python-3.x stdout

Python 版本 - 3.5.2 操作系统 - Ubuntu 16.04 LTS

我目前正在使用 stdout 和 print 语句写入终端。 我只想捕获 sys.stdout.write 命令的输出,而不是打印命令 因此,例如,如果我的代码是 -

import sys
sys.stdout.write("Hello")
print("PRINT")

我只想捕获“Hello”而不是“PRINT”。

我目前正在使用这个:

x = subprocess.run(['python3 test.py'] , shell = True , stdout = subprocess.PIPE).stdout.decode('utf-8')

这给了我这个输出:

['HelloPRINT', '']

最佳答案

print() 使用 sys.stdout.write() 来显示文本。

除了 suproccess 之外,只能看到系统发送的文本,它不知道您使用什么向系统发送文本。

您只能在代码中将 print() 重定向到 sys.stderr

import sys
sys.stdout.write("Hello")
print("PRINT", file=sys.stderr)

然后当您在控制台中运行时,您仍然会看到所有文本,但当您使用 subprocess 时,您只会得到 sys.stdout

如果你在控制台中使用,你也只会在文件中得到 stdout

python script.py > stdout.txt

或者你重定向到其他程序

python script.py | sort

除了 print(... ,file=sys.stderr) 你也可以使用 sys.stderr.write("PRINT\n") 但是你有手动在末尾添加"\n"

关于python - 在 python 中捕获 ONLY stdout 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57140054/

相关文章:

python - 动态决定使用哪个浏览器

适用于 Windows 操作系统的 Python、Gtk+ 部署(多平台)

python - Pandas 类别 : keep only most common ones and replace rest with NaN

python-3.x - dag.py引发: "airflow.exceptions.AirflowException: Task is missing the start_date parameter",,但在代码中给出

python - 连接 2 modbus slave pymodbus 时出错

linux - 从 cron 运行时,Perl 脚本不会将 STDOUT 输出到文件

python - 将标准输出从多个进程重定向到 python 日志记录模块

python - 如何将带有逗号分隔项的字符串转换为 Python 中的列表?

python - split headless 选项被拒绝

c++ - 将字符串变量的值与一些文本链接起来,并将其打印到 C++ 中的标准输出