4

I would like to retrieve the stdout, stderr and resultcode of a module function called from the main program. I thought subprocess was the key, but I don't succeed submitting the module function to subprocess.

What I have:

#my_module.py
def run(args):
    do stuff
    print this
    return THAT
if name == "__main__":
    args = read_args()
    run(args)

.

#my_main_script.py
import subprocess as sp
import my_module
p = sp.Popen(my_module.run(args), stdout=sp.PIPE, stderr=sp.PIPE)
out, err = p.communicate()
result = p.resultcode

What occurs: Apparently the subprocess module does something with THAT returned from the my_module.run() provoking the crash:

if THAT = list_of_lists error: AttributeError: "sublist" object has no attribute rfind

if THAT = ["a","b",0] error: TypeError: execv() arg 2 must contain only strings
if THAT = ["a","b"] error: OSError: [Errno 2] No such file or directory

So subprocess apparently wants THAT to be a list containing path to files ???

1 Answers1

3

You are not using subprocess in the right way :

sp.Popen(["./my_module.py", "arg1", "arg2"], stdout=sp.PIPE, stderr=sp.PIPE)

By the way, you wouldn't get any resultcode if you does not exit properly your program with the sys.exit(retcode) function.

The final scripts would look like this :

#my_module.py
def run(args):
    do stuff
    print this
    return THAT

if name == "__main__":
    import sys
    args = read_args()
    sys.exit(run(args))

#my_main_script.py
import subprocess as sp

p = sp.Popen(["./my_module.py", "arg1", "arg2"], stdout=sp.PIPE, stderr=sp.PIPE)
out, err = p.communicate()
result = p.returncode
FunkySayu
  • 6,072
  • 7
  • 31
  • 55
  • 1
    how will the module receive the arguments then? (they already are in the argparse format) Can't I just launch the run function ? –  Jul 20 '15 at 09:54
  • Edited. Sorry i forgot this part. – FunkySayu Jul 20 '15 at 09:56
  • 1
    So I should reconvert all arguments from my argparser to a string format, and then run the main with the converted arguments ? No way at all to simply call a function in sp.Popen() ? –  Jul 20 '15 at 09:57
  • Forget what I say before about another solution. I *think* it's the right way to deal with it. Maybe someone else will come with another possibility, but currently I only see this one. – FunkySayu Jul 20 '15 at 10:02
  • 1
    Else, you can do it this way : http://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call – FunkySayu Jul 20 '15 at 10:02
  • 1
    Perfect ! This last option suits perfectly my necessity ! Im still wondering what the subprocess was expecting as a return from my function... :/ Thanks for your help ! –  Jul 20 '15 at 10:05
  • I think you don't really get what subprocess is. Do you want me to explain it ? – FunkySayu Jul 20 '15 at 11:01