我正在从 Excel 运行一个调用 python 脚本的宏。我在 PC 上的一个位置安装了 Python 3.11.5,在另一位置安装了 3.12.1。当我使用 3.11.5 调用脚本时
vbaShell.Run """C:\Python311\python.exe""" & " " & """D:\Users\admin\Desktop\Projects\python\getDataTests.py""" & " " & """" & Workbook & """" & " " & """" & path & """"
运行没有任何问题。但是当我用 3.12.1 运行它时
vbaShell.Run """C:\Users\admin\AppData\Local\Programs\Python\Python312\python.exe""" & " " & """D:\Users\admin\Desktop\Projects\python\getDataTests.py""" & " " & """" & Workbook & """" & " " & """" & path & """"
我看到 python shell 闪烁,然后什么也没有,我正在寻找一些故障排除帮助,因为我没有收到错误消息并且 shell 立即关闭。还有关于为什么 3.11 可以工作但 3.12 不行的任何建议。我调用的 .py 脚本中不应该存在任何兼容性问题。
这对我有用:
Sub Tester()
Dim newShell As Object, cmd As String
Dim PythonExePath As String, PythonScriptPath As String, arg1 As String, arg2 As String
Set newShell = VBA.CreateObject("Wscript.Shell")
PythonExePath = "C:\Python\Python39-32\python.exe"
PythonScriptPath = "C:\Temp\VBA\test.py"
arg1 = "Arg1 Here"
arg2 = "Arg2Here"
'change /k to /c to allow the cmd window to close after running the script
cmd = "cmd /k "" ""<exe>"" ""<script>"" ""<arg1>"" ""<arg2>"" """
cmd = Replace(cmd, "<exe>", PythonExePath)
cmd = Replace(cmd, "<script>", PythonScriptPath)
cmd = Replace(cmd, "<arg1>", arg1)
cmd = Replace(cmd, "<arg2>", arg2)
newShell.Run cmd, vbNormalFocus
End Sub
Python 脚本(仅将任何脚本参数打印到标准输出):
import sys
print (sys.argv[1:]);
输出: