At UNIX command line, one can run ls -la $HOME
. How to trigger this from Mathematica notebooks?
Run["!ls -la $HOME"]
32512
Returns some integer -- what is it? -- but not the normal output.
Answer
The Run
command returns the exit code of the program being run. In your case, the program is "!ls" which probably doesn't exist on your system (If you try
sh -c '!ls -la $HOME'
you'll also get an error). Why it returns 32512
instead of 127
(which is the return value I get by the shell) I don't know; however I notice that $32512 =127\cdot 256$, so I guess it's in order to better distinguish valid exit codes (usually telling about errors during the execution) from errors occurring when trying to execute the command (like not finding the executable).
If you start a raw kernel and type
Run["ls -la $HOME"]
(without exclamation mark) you'll see the output of the ls
command on standard output, and a returned value of 0
(the exit code of ls
). If you do it from a notebook, the standard out will be the one Mathematica was started with; if started from a terminal, that's where the output will happen, otherwise it will end up elsewhere or even nowhere (in my test, the directory listing ended up in .xsession-errors
because I started Mathematica through the desktop environment).
If you are interested in the actual output, you have to use a file reading command, and use the special "!" syntax; for example Import
as suggested by user18792,
Import["!ls -la $HOME", "Text"]
giving you all the output in a single string, or ReadList
as suggested by Gustavo Delfino,
ReadList["!ls -la",String]
giving you a list of strings, each containing a single line of the output.
Note that the exclamation mark says you want to get the output of a command instead of the contents of a file (whose name would have gone at that point otherwise). That's why you don't put the exclamation mark at the Run
command: Its argument is not a file to read, but already a command to execute, thus you don't need (and cannot use) the exclamation mark "escape" to use a command instead of a file.
If you need both the output and the exit code, apparently in version 10 you can use RunProcess
(I can't check that because I don't have access to v10). From the documentation, I get that the command would look like the following:
RunProcess[{"ls", "-la", Environment["HOME"]}]
Comments
Post a Comment