Get an error message from a SQL query back into Python
Question: I need to be able to tell if SQL queries kicked off by Python have failed. So
far I have:

    
    
    import subprocess
    p = subprocess.Popen(['sqlcmd', '-E -m-1 -S 1070854A\AISP -i NewStructures.sql >>process.log'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    print out
    print err
    

But it is not liking the SQLCMD parameters. Output says

    
    
    Sqlcmd: '-E -S 1070854A\AISP -i NewStructures.sql': Unknown Option. Enter '-?' for help.
    

These parameters work when typing them into the command line.

Thanks.


Answer: `'-E -m-1 -S 1070854A\AISP -i NewStructures.sql >>process.log'` is interpreted
as one single argument, that's why you get this error. You need to split the
arguments to make this work.

Seen as you're trying to use a redirection in your shell command, you could
use something like this:

    
    
    import subprocess
    with open('process.log', 'ab') as logfile:
        logfile.seek(0, 2)
        p = subprocess.Popen(['sqlcmd', '-E', '-m-1', '-S', '1070854A\AISP', '-i', 'NewStructures.sql'], stdout=logfile, stderr=subprocess.PIPE)
        out, err = p.communicate()
    

`out` will be emty anyway, as stdout is redirected to a file.

Redirection using `>` or `>>` only works with `shell=True`.

