[英]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.