如何使用子进程捕获SQLCMD的Msg字符串?

问题描述 投票:0回答:1

我通过子进程包调用sqlcmd,虽然运行正常,但我无法捕获SQLCMD的失败信息并中止部署。虽然运行正常,但我无法捕获SQLCMD的失败信息并中止部署。

这是我的代码。

 try:
                            print(check_output(
                                'sqlcmd -S ' + args.serverName + ' -d ecomm -U ' + args.userName + ' -P ' + args.password + ' -i ' + fpath + '',
                                shell=True))
 except CalledProcessError as e:
                            print('Deployment of files has failed somehow. Please find below the bread crumbs...')
                            logging.info('Deployment of files has failed somehow. Please below the bread crumbs...')
                            print(e.output)
                            logging.info(e.output)
 finally:
                            print('Successfully deployed ' + fname + ' to the database')
                            logging.info('Successfully deployed ' + fname + ' to the database')

我得到了下面的输出。

Going ahead with deployment
Going to invoke sqlcmd cli to deploy dbo.uspFindProducts_SP.StoredProcedure.sql...
b"Msg 156, Level 15, State 1, Server IDEA-PC\\SQLEXPRESS, Procedure uspFindProducts_SP, Line 18\r\nIncorrect syntax near the keyword 'AS'.\r\n"
Successfully deployed dbo.uspFindProducts_SP.StoredProcedure.sql to the database

Check_output 正在打印 b"Msg 156, Level 15, State 1, Server IDEA-PC\\SQLEXPRESS, Procedure uspFindProducts_SP, Line 18\r\nIncorrect syntax near the keyword 'AS'.\r\n"

理想情况下,在打 Msg 字符串,它应该进入异常块并中止部署。

如何捕捉 Msg 字符串,这样每当出现这样的字符串语句时,部署就会被中止。

敬告

python python-3.x subprocess sqlcmd
1个回答
0
投票

我在回答我自己的问题......

我已经解决了上面的用户故事,通过使用字节到utf-8的解码组合和 shlex.split().

如果 shlex.split() 不为空,则中止部署。

sub = subprocess.run(["sqlcmd", "-S", .....], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
decoded_stdout = sub.stdout.decode('utf-8')
stdout_list = shlex.split(decoded_stdout)

if stdout_list != 0:
     print('Don't do the deployment')
else:
     print('do the deployment')

这是输出和日志。

2020-05-02 17:44:52,874:INFO:395:Going to invoke sqlcmd cli to deploy dbo.uspFindProducts_SP.StoredProcedure.sql...
2020-05-02 17:44:53,159:INFO:399:Msg 156, Level 15, State 1, Server IDEA-PC\SQLEXPRESS, Procedure uspFindProducts_SP, Line 18

Incorrect syntax near the keyword 'AS'.


2020-05-02 17:44:53,159:INFO:403:Something failed and we have got a non-zero return code

现在,错误已经被很好地解码为utf-8,并且错误字符串会被分割成一个列表,并使用 shlex.split().祝大家有一个美好的一天! :)

© www.soinside.com 2019 - 2024. All rights reserved.