-1

我需要能够判断由 Python 启动的 SQL 查询是否失败。到目前为止,我有:

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

但它不喜欢 SQLCMD 参数。输出说

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

这些参数在将它们键入命令行时起作用。

谢谢。

4

1 回答 1

0

'-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.

于 2013-04-23T13:44:34.600 回答