將程式輸出重定向到檔案失敗

將程式輸出重定向到檔案失敗

所以我有一個程序,我們稱之為 foo。我正在嘗試使用以下命令將其終端輸出重定向到檔案。

foo > ./someFile.txt

現在,當我運行該命令時,會建立 someFile.txt 但它是空的。關於如何重定向終端輸出有什麼建議嗎?

答案1

someFile.txt將建立一個文件是預期的行為。該文件是否包含任何內容取決於您的程式foo應該執行的操作。

無論您遇到什麼問題,似乎都與輸出重定向無關。您可以嘗試以下命令作為測試:

cat > someFile.txt

鍵入任何內容。您輸入的任何內容都將被重定向到(以+someFile.txt結尾)。ctrld

順便說一句,輸出檔案是由您的 shell 建立的,而不是由您的程式建立的foo。即使您輸入不存在的命令,仍然會建立輸出檔案(空):

/bin/nonexistent > zzz

答案2

另一種可能性是,如果標準輸出沒有指向互動的地方,則foo使用並且不向標準輸出寫入任何內容。isatty

概要

#include <unistd.h>
int isatty(int fd);

描述 isatty() 函數測試 fd 是否是引用終端機的開啟檔案描述子。

這個簡短的 Python 程式演示了這一點:

import sys, os

if sys.stdout.isatty():
    print "Hello, tty %s" % os.ttyname(1)
else:
    print "stdout: not a typewriter: how boring"

正如這個簡短的 C 程序一樣:

#include <stdio.h>
#include <unistd.h>

int main (void) {
    if ( isatty(stdout) ) {
        printf("Hello, tty %s\n", ttyname(1));
    } else {
        printf("stdout: not a typewriter: how boring\n");
    }
    return 0;
}

兩個程序具有相同的行為:

$ ./isatty > notatty ; cat notatty
stdout: not a typewriter: how boring

$ ./isatty.py
Hello, tty /dev/pts/1

$ ./isatty | cat
stdout: not a typewriter: how boring

程式可以根據是否重定向來選擇列印方式、列印內容以及是否列印。

這樣做的一個常見應用是避免將終端(\e[33;1m等)讀取的用於文字著色的 ANSI 轉義序列寫入文件,這看起來很醜陋並使解析器感到困惑。

答案3

我有同樣的問題。我的程式日誌沒有如預期寫入 [stdout],而是寫入 [stderr]。因此,解決方案是重定向 [stdout] 和 [stderr]:

foo >> someFile.txt 2>&1

相關內容