将pymssql stdout转换为变量 [英] stdout pymssql to variable

查看:107
本文介绍了将pymssql stdout转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索运行中的结果表单

Im trying to retrieve the result form running

import pymssql
conn = pymssql.connect(server='IP', user='domain\user', password='PSWD', tds_version='8.0')
cursor = conn.cursor()
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = 'jobname'")

将作业添加到提示中以进行处理时,它不会返回任何内容,但是当作业未运行时,它将返回诸如测试用例之类的东西

when it add the job to the cue to process it wont return anything, but when the job wasn't runned it will return stuff like in a case for testing

Traceback (most recent call last):
  File "shared/python3", line 85, in <module>
    cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = ''")
  File "pymssql.pyx", line 467, in pymssql.Cursor.execute (pymssql.c:7533)
pymssql.OperationalError: (14262, "The specified @job_name ('') does not exist.DB-Lib error message 14262, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")

在这种情况下,错误指出Job_name不存在.我要做的是将结果放在一个字符串变量中,我可以解析该字符串变量以进行错误控制...

In this case the error is pointing out tha the Job_name doesn't exist. What I want to do is put the result on a string variable that I can pars for error control...

我已经尝试过了:

import sys

# Store the reference, in case you want to show things again in standard output
old_stdout = sys.stdout

# This variable will store everything that is sent to the standard output
result = StringIO()
sys.stdout = result

# Here we can call anything we like, like external modules, and everything that they will send to standard output will be stored on "result"
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = 'jobname'")

# Redirect again the std output to screen
sys.stdout = old_stdout

# Then, get the stdout like a string and process it!
result_string = result.getvalue()
process_string(result_string)

链接.但无法正常工作.

推荐答案

您看到的是回溯,因为您没有处理作业名称不存在时发生的异常.如果要捕获错误消息,则只需捕获异常即可.作为通用示例,不只是做

You are seeing the traceback because you are not handling the exception that occurs when the job name does not exist. If you want to capture the error message you can simply catch the exception. As a general-purpose example, instead of just doing

crsr.execute(sql)

你可以做

try:
    crsr.execute(sql)
except Exception as e:
    (error_code, error_message) = e

,然后使用error_codeerror_message值将它们写入日志文件,或将它们吐到控制台中.

and then use the error_code and error_message values to write them to a log file, or spit them out to the console, or whatever.

这篇关于将pymssql stdout转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆