将外部系统终端的输出重定向到文件

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

我在 anaconda [Windows] 的 spyder 中打开了一个

test.py
文件。当我在
current console
中执行脚本时,脚本不断卡住。我注意到当我将配置更改为
Execute in an external system terminal
[
ctl + F6
]

时不会发生这种情况

我的脚本正在向屏幕输出一些信息,我想将这些信息保存到文件中。

我该怎么做?

最好的问候

python python-3.x anaconda spyder
2个回答
2
投票

您可以使用

>
运算符将 python 程序的输出重定向到一个单独的文件中。例如,假设您有一个文件
script.py
。您可以通过运行重定向终端中的输出

python script.py > out.txt

在哪里

out.txt
是您正在写入标准输出的文件的名称。

这是另一个堆栈溢出帖子,如果您还想重定向标准错误/附加到文件,您可能会发现它有帮助:How to redirect and append both standard output and standard error to a file with Bash


0
投票

来自评论中的澄清:

仅使用 > 将输出重定向到文件(这很好!)。但它不再输出到屏幕。这是一个部分解决方案

我知道 OP 既要将输出打印到终端又要将其保存到文件,因此解决方案

tee
命令将输出打印到文件并使用管道重定向将其显示在屏幕上。
tee
命令读取标准输入并将其写入标准输出(屏幕)和一个或多个文件。

这是一个示例,说明如何使用

tee
和管道重定向来实现此目的:

command | tee output.txt

在此示例中,

command
表示您要捕获其输出的命令。管道 (
|
) 将
command
的输出重定向到
tee
,然后将其写入屏幕和指定的文件(在本例中为
output.txt
)。在您的情况下,您将使用
python myfile.py
命令,因此:

python myfile.py | tee output.txt

请注意,

tee
将覆盖文件的内容(如果它们已经存在)。如果要将输出附加到现有文件,则可以使用
-a
(或
--append
)选项和
tee
:

command | tee -a output.txt

在 Unix(例如 Linu)中

tee
是内置的,在 Windows 中,您可以在这里下载
tee
和其他实用程序:https://gnuwin32.sourceforge.net/packages/coreutils.htm

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