我不認爲你可以做到這一點(至少在* nix系統上;我沒有Windows/Mac系統的便利),因爲system
似乎無形地返回了執行命令返回的值,而R doesn似乎不會將命令的輸出重定向到R控制檯。
這是因爲您的終端的stdout
與R控制檯「stdout」不一樣。你在R會話中看到的是終端的stdout
和R處理輸出的混合。 capture.output
正在尋找R進程的輸出,而不是所有從父進程輸出到stdout
。
你可以啓動一個打印到stdout
的進程,把它放在後臺,然後啓動R ...,你會在你的「R輸出」中看到該進程的輸出,類似於你運行從system("ping -c5 8.8.8.8")
R.
[email protected]: /home/josh
> ping -c5 8.8.8.8 & R
[1] 5808
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=46 time=39.9 ms
R version 3.2.4 Revised (2016-03-16 r70336) -- "Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> 64 bytes from 8.8.8.8: icmp_seq=2 ttl=46 time=38.1 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=46 time=38.3 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=46 time=38.4 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=46 time=38.3 ms
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4003ms
rtt min/avg/max/mdev = 38.176/38.656/39.986/0.703 ms
> q()
Save workspace image? [y/n/c]: n
[1]+ Done ping -c5 8.8.8.8
[email protected]: /home/josh
>
謝謝!我意識到這一點,但如果我能找到一種方法來捕獲'system()'的輸出,我就不會使用它。在Joshua Ulrich的回答下看到我的評論。 –
@Yihui它不是*那*壞 - 特別是知道例如'system'中的'ignore.stdout'和'ignore.stderr'選項只需添加'>/dev/null'或'2>/dev/null'重定向到'command' :) – daroczig