开发者

Very weird behavior when running external command in Mathematica

Why does

Import["!python --version", "Text"]

work on the commandline but not in the frontend of Mathematica 8 (running on a Mac)?

Shell:

"Python 2.7.1 -- EPD 7.0-2 (64-bit)"

Frontend:

""

Update:

Ok, the path is not (really) the problem, as

Import["!w开发者_如何转开发hich python", "Text"]

yields

"/usr/bin/python"

in the frontend and

"/Library/Frameworks/EPD64.framework/Versions/Current/bin/python"

in the shell (which is a different python version I have installed on my system). Nevertheless, neither

Import["!/usr/bin/python --version", "Text"]

nor

Import[
"!/Library/Frameworks/EPD64.framework/Versions/Current/bin/python --version",
"Text"]

yield the correct output in the frontend. But the usage of different shells in the frontend and the terminal version could be a hint to why Mathematica is misbehaving.


python --version writes its response to the standard error stream, but Import only captures the standard output stream. To see the response, redirect stderr to stdout. In most shells (even Windows), this can be achieved using the magic incantation 2>&1:

Import["!python --version 2>&1", "Text"]

Front-end Different From Command-line?

The Import command appears to function differently when run in the command-line version of Mathematica, but appearances can be deceiving. Here is a transcript:

$ math
Mathematica 8.0 for Microsoft Windows (64-bit)
Copyright 1988-2011 Wolfram Research, Inc.

In[1]:= Import["!python --version","Text"]
Python 2.6.4

Out[1]=

Note that Out[1] is blank. The version string appears in the transcript, but this is due to the fact that the standard error stream is being displayed in the terminal window, interspersed with the standard output from Mathematica. This is even more clear if we assign the result to a variable and (attempt to) suppress the output using ;:

In[2]:= v=Import["!python --version","Text"];
Python 2.6.4

In[3]:= v

Out[3]=

There shouldn't have been any output, but we still see the standard error stream displayed in the terminal window. v is blank, showing that the value of the Import expression was blank as well.


WReach has the answer to your problem. However, my point still remains that the instance of the shell invoked by mathematica does not have the path variable set correctly. Here's some info from mine:

Very weird behavior when running external command in Mathematica

The shell is correct, but the path is the default path. So source my modified path and then invoke python --version:

Very weird behavior when running external command in Mathematica

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜