使用将Mathematica脚本的输出重定向到管道而不是stdout子流程.Popen生成空字符串

2024-09-28 03:24:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Mathematica脚本,可以作为bash可执行文件从终端运行。我想从Python内部运行它并得到结果。这是我想使用的代码:

proc = subprocess.Popen(["./solve.m", Mrefnorm, Mvert, Mcomp, Mangle],
        stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result, err = proc.communicate()

不幸的是,结果是一个空字符串。但是,当我运行此代码时,结果会像我预期的那样打印到终端窗口:

^{pr2}$

我发现这个answer是为有windows的人设计的,它和我遇到的问题完全相同。不幸的是,他的解决方案与防火墙软件沙箱进程有关。我已经禁用了我的检查是否可以解决它,但它没有。我试过评论家们对他的问题所提到的一切,但都没有成功。在

总之,Mathematica脚本在这两种情况下都会运行(两种情况都需要大约5秒),但是当我使用PIPE时,我无法从脚本获得输出。在


Tags: 代码脚本bash终端可执行文件情况procsubprocess
3条回答

如果Mathematica不喜欢重定向的stdout,那么您可以尝试通过提供一个伪tty来蒙蔽它:

import pipes
from pexpect import run # $ pip install pexpect

args = ["./solve.m", Mrefnorm, Mvert, Mcomp, Mangle]
command = " ".join(map(pipes.quote, args))
output, status = run(command, withexitstatus=True)

你也可以use stdlib ^{} module directly to capture the output。在

如果您想获得单独的stdout/stderr;可以尝试解决the bug mentioned by @Wayne Allen。在

我不知道这是为什么,但我让它这样工作:

 proc=subprocess.Popen('fullpath/math -initfile  fullpath/script.m' ,
        shell=True,
        stdout=subprocess.pipe )

由于某些原因,arg list的list形式不起作用,-script也不起作用。在

刚刚检查过你可以传递额外的参数很好的添加到字符串中

^{pr2}$

通过$CommandLine访问脚本中的参数

(mathematica 9,python 2.4.3,redhat)

相关问题 更多 >

    热门问题