簡體   English   中英

Ruby中的輸出重定向故障排除

[英]Output redirection troubleshooting in Ruby

所以我試圖暫時將輸出重定向到文件:

  prev_std = STDOUT

  $stdout.reopen(@filename, 'w:UTF-8')

  # stuff happens here with @filename and lots of output

  $stdout = prev_std

但是當我這樣做時,似乎無法在之后將其重定向回去。 我在這里做錯了什么?

STDOUT是代表標准輸出的常數,它是一個IO對象。 $stdout是一個全局變量,其默認值通常是STDOUT本身,默認情況下,它們都指向同一對象:

$stdout.object_id == STDOUT.object_id => true

如果對其中一個調用方法,則另一個將受到影響。 因此,如果您使用$stdout調用方法,它也會在STDOUT生效。 $stdout上調用reopen也會影響STDOUT (即使它是一個常量)。

如果要臨時將輸出重定向到文件,然后將其還原到標准輸出,則應$stdout分配一個新的IO對象:

$stdout = File.open('/path/to/file', 'w:UTF-8')
puts "this will go to the file"
$stdout = STDOUT
puts "this will go to standard output!"

另請參閱以下問題:

您正在STDOUT上調用reopen ,因為$stdout只是一個指向同一對象的全局變量。 這將永久更改STDOUT

那這個呢:

$stdout = File.open(@filename, 'w:UTF-8')

# ...

$stdout = prev_std

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM