Как перехватить строку Msg в SQLCMD, используя подпроцесс? - PullRequest
0 голосов
/ 02 мая 2020

Я вызываю 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, чтобы при появлении такого оператора строки развертывание прерывалось.

С уважением

1 Ответ

0 голосов
/ 02 мая 2020

Я отвечаю на свой вопрос, ребята ...

Я решил вышеупомянутую историю пользователя, используя комбинацию байтов для декодирования 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(). Всем хорошего дня! :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...