Running external commands without going through a shell?

22 ビュー (過去 30 日間)
Joël Schaerer
Joël Schaerer 2020 年 12 月 3 日
コメント済み: Joël Schaerer 2020 年 12 月 21 日
The Matlab system() command allows the user to run external commands. To do this, it spawns a shell, and uses it to run the provided command. (see https://fr.mathworks.com/help/matlab/ref/system.html)
This behavior is great for interactive use. However, for production code, it can cause issues with special characters as the shell will have a tendancy to over-interpret the given commands. So, for example, a directory with parenthesis in its name can cause shell errors and prevent the command from executing properly.
In the Python world, the subprocess module has a way to run commands directly, without spawning a shell (the "shell" argument):
Does Matlab have an equivalent? I know people have proposed various regular expressions to escape strings, but that is just not robust enough.

採用された回答

Jan
Jan 2020 年 12 月 16 日
Maybe this works for you:
runtime = java.lang.Runtime.getRuntime();
process = runtime.exec('program arg1 arg2'); % non-blocking
% Continue Matlab processing in parallel to spawned process ...
% ...or:
rc = process.waitFor(); % block Matlab until external program ends
rc = process.exitValue(); % fetch an ended process' return code
  1 件のコメント
Joël Schaerer
Joël Schaerer 2020 年 12 月 21 日
Thanks! I didn't get a chance to try it yet, but will try to report back when I do.

サインインしてコメントする。

その他の回答 (1 件)

Nitin Kapgate
Nitin Kapgate 2020 年 12 月 16 日
You can execute operating system commands from the MATLAB command line using the ! operator as an alternative to the system function. The exclamation point character (!), sometimes called bang, is a shell escape. The ! character indicates that the rest of the input line is a command to the operating system.
Use ! to call utilities or other executable programs without quitting MATLAB.
For example, the following code opens the Microsoft Excel on a WINDOWS platform:
!excel.exe
After the external program completes or you quit the program, the operating system returns control to MATLAB.
To run the application in background mode or display the output in a separate window, add & to the end of the line.
For example, the following statement opens the Microsoft Excel program and returns control to the command prompt so that you can continue running MATLAB commands:
!excel.exe &
  1 件のコメント
Joël Schaerer
Joël Schaerer 2020 年 12 月 21 日
Hi, I don't think the bang operator changes anything regarding my problem.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

製品


リリース

R2013b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by