MATLAB的"system"命令的更安全替代品 [英] Safer alternative to MATLAB's `system` command

查看:143
本文介绍了MATLAB的"system"命令的更安全替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用MATLAB的system命令来获取某些linux命令的结果,例如下面的简单示例:

I have been using MATLAB's system command to get the result of some linux commands, like in the following simple example:

[junk, result] = system('find ~/ -type f')

这可以按预期工作,除非用户同时在MATLAB的命令窗口中键入 .在较长的find命令中,这并不罕见.如果发生这种情况,那么用户的输入似乎会与find命令的结果混淆(然后事情中断了).

This works as expected, unless the user types into MATLAB's command window at the same time. Which during a long find command is not uncommon. If this happens then the user's input seems to get mixed up with the result of the find command (and then things break).

作为示例,代替:

/path/to/file/one
/path/to/file/two
/path/to/file/three
/path/to/file/four

我可能会得到:

J/path/to/file/one
u/path/to/file/two
n/path/to/file/three
k/path/to/file/four

为了便于演示,我们可以运行以下命令:

In order to demonstrate this easily, we can run something like:

[junk, result] = system('cat')

在命令窗口中键入内容,然后按CTRL + D关闭流. result变量将是您在命令窗口中键入的变量.

Type something into the command window and press CTRL+D to close the stream. The result variable will be whatever you typed in to the command window.

我有没有更安全的方法可以从MATLAB调用系统命令,而又不会冒输入损坏的风险?

Is there a safer way for me to call system commands from MATLAB without risking corrupted input?

推荐答案

感谢安德鲁·扬克(Andrew Janke)帮助我找到此解决方案.

Thanks goes to Andrew Janke for helping me find this solution.

要轻松重现该错误,我们可以运行以下命令:

To easily reproduce the error we can run the command:

[ret, out] = system('sleep 2');

如果我们在运行时键入一些字符,则out变量将被我们键入的内容污染.

If we type some characters while this is running, the out variable will be contaminated with what we typed.

此问题的解决方案是从/dev/null重定向标准输入,如下所示:

The solution to this problem is to redirect stdin from /dev/null like the following:

[ret, out] = system('sleep 2 < /dev/null');

这可以防止out变量被用户输入污染.

This stops the out variable from being contaminated by user input.

有趣的是,这似乎可以解决当前MATLAB会话的原始测试用例(已在R2014a OSX和R2013b Linux上进行了测试),因此,如果再执行[ret, out] = system('sleep 2');,输出将不再受到用户输入的污染.

Interestingly though this seems to fix the original test-case for the current MATLAB session (tested on R2014a OSX and R2013b Linux) so if we do another [ret, out] = system('sleep 2'); the output is no longer contaminated by user input.

这篇关于MATLAB的"system"命令的更安全替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆