从SQLServer运行python脚本上面的代码运行良好-它运行

我已经被这个问题困扰了一段时间,但如果我做对了 – 没有什么比这更好的了。我正在尝试使用 xp_cmdshell 使用以下代码从 SQL Server 运行 python 脚本

EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
EXEC xp_cmdshell 'python.exe "FilePath"'
EXEC sp_configure 'xp_cmdshell', 0
RECONFIGURE
GO

上面的代码运行良好 – 它运行 python 脚本(我可以说它运行是因为 python 脚本将我的一些数据保存在 Excel 表中)。在 python 脚本中,我有一段代码可以在 excel 表上进行一些格式化:

import xlwings as xw
# create an excel instance app object as a context manager to make sure files are closed safely
app = xw.App(visible = True)
# open Policies Comparison workbook
excel_book = app.books.open(fr'FilePathDummy_Name.xlsx')
# fetch active sheet 
ws = excel_book.sheets.active
# select Cell A1 and press Ctrl + A
tbl_range = ws.range("A1").expand('table')
# create table 
ws.api.ListObjects.Add(1, ws.api.Range(tbl_range.address))
# save and close workbook and app object
excel_book.save()
excel_book.close()
app.quit()

当我从 Python IDE(如 anaconda 提示符或 VSCode)运行此代码时,它运行完美。但是,当我使用上面显示的命令 xp_cmdshell 从 SQL Server 调用 python 脚本时,它会失败并出现以下错误:

我可以肯定地说,上述错误与上面的 xlwings 部分有关。那是因为如果我删除 xlwings 部分,我的 python 脚本中的剩余代码将正确运行。从回溯中,我可以理解访问被拒绝。因此,我尝试了一些想法,例如使用 xw.App(visible = False) 而不是 xw.App(visible = True) 并尝试使用上下文管理器运行。但是这些功能很有效。

我是 xlwings 和 shell 命令的新手。我发现此错误与其他 stackoverflow 问题和答案中的 pywin32 库有关,如下所示:Win32com codes not working on IISImportError: No module named win32com.client

我假设 xlwings 库或 xp_cmdshell 对 pywin32 库进行了某种调用以执行上述操作。我还发现这个库是一个用于与 Windows 对话的高级库,这表明我很难调试。因此,我正在寻求您的专家帮助。我已经被这个问题困扰了一段时间,并且非常感谢一个可以探索的方向,或者帮助我找出我做错了什么。

© 版权声明
THE END
喜欢就支持一下吧
点赞259赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容