Python call function from module in a subprocess
Question: 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 ???


Answer: 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
    

