Redirecting output from Mathematica Script to PIPE Instead of stdout Using subprocess.Popen Output string Null String

I have a Mathematica script that I can execute as executable bash from Terminal. I want to run it from Python and get the result. This is the code I wanted to use:

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

Unfortunately, the result is an empty string. However, when I run this code, the result is printed in the terminal window, as expected:

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

I found this answer for someone with windows, and this is the same as what I have. Unfortunately, his decision is related to his firewall software isolating the processes. I have already disabled mine to check if this will resolve it, and it is not. I tried everything that commentators mentioned on his subject without success.

So, a Mathematica script works in both cases (it takes about 5 seconds for both), but when I use PIPE, I can not get the result from the script.

+3
source share
3 answers

If Mathematica does not want to redirect stdout, you can try to trick it by providing pseudo-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)

You can also use the stdlib module ptyto capture output .

If you want to get a separate stdout / stderr; you can try to get around the error mentioned by @Wayne Allen .

+1
source

I'm not sure why this is so, but I did it like this:

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

For some reason, the arg list form is not working, but -scriptnot working.

You just checked, you can pass additional arguments by simply adding to the string

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

access arguments in script via $CommandLine

(math 9, python 2.4.3, redhat)

+1
source

All Articles