vbaShellRun for Python

Question:

I am running a macro from Excel that calls a python script. I have Python 3.11.5 installed in one location on my PC and 3.12.1 installed at another. When I call the script using 3.11.5

vbaShell.Run """C:Python311python.exe""" & " " & """D:UsersadminDesktopProjectspythongetDataTests.py""" & " " & """" & Workbook & """" & " " & """" & path & """"

It runs without any issue. But when I run it with 3.12.1

vbaShell.Run """C:UsersadminAppDataLocalProgramsPythonPython312python.exe""" & " " & """D:UsersadminDesktopProjectspythongetDataTests.py""" & " " & """" & Workbook & """" & " " & """" & path & """"

I see the python shell flash and then nothing, I’m looking for some help troubleshooting since I am not getting an error message and the shell immediately closes. Also any suggestions as to why 3.11 would work but not 3.12. There shouldn’t be any compatibility issues within the .py script I am calling.

Asked By: Mdurocher

||

Answers:

This works for me:

Sub tester()

    Const EXE_PATH As String = "C:PythonPython39-32python.exe"
    Const SCRIPT_PATH As String = "C:TempVBAtest.py"

    'keep cmd window open - no args
    RunScriptWithArgs EXE_PATH, SCRIPT_PATH, True
    
    'keep cmd window open - 2 args
    RunScriptWithArgs EXE_PATH, SCRIPT_PATH, True, "Arg1 Here", "Arg2Here"
    
    'same again but close cmd after execution
    RunScriptWithArgs EXE_PATH, SCRIPT_PATH, False, "Arg1 Here", "Arg2Here"

End Sub


Sub RunScriptWithArgs(exePath As String, scriptPath As String, _
                      keepOpen As Boolean, ParamArray args())

    Dim cmd As String, arg, allArgs
    cmd = "cmd " & IIf(keepOpen, "/k", "/c") & " "" ""<exe>"" ""<script>"" <args> """
    cmd = Replace(cmd, "<exe>", exePath)
    cmd = Replace(cmd, "<script>", scriptPath)
    For Each arg In args
        allArgs = allArgs & " """ & arg & """"
    Next arg
    cmd = Replace(cmd, "<args>", allArgs)
    'Debug.Print cmd
    VBA.CreateObject("Wscript.Shell").Run cmd, vbNormalFocus
End Sub

Python script (just prints any script arguments to stdout):

import sys
print (sys.argv[1:]);

Output:

enter image description here

Answered By: Tim Williams

It was a python package issue, but since I was not getting any error messages this was hard to determine. I ran the python script from cmd outside of excel and finally got an error.

Answered By: Mdurocher
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.