首页 > 解决方案 > 在执行路径中有空格的 VBA 中运行 Python

问题描述

我编写了一个 Python 脚本来执行我想通过 Excel VBA 运行并在 Excel 中显示结果的计算。为了可用于不同的用户,我正在尝试编写一个代码,该代码将根据他们输入的用户名生成 Python 执行和 Python 脚本的路径,因为这是路径中唯一会改变的东西。

有些人的用户名中有空格,这会在尝试在命令提示符下运行 Python 时出现问题。

有类似的问题,但我还没有找到解决方案。我尝试在执行路径的开头和结尾添加三重双引号,例如

"""C:\Users\Claire Watson\anaconda3\python.exe"""

命令提示符中的结果是“C:\Users\Claire”无法识别。但是,这确实适用于 Python 脚本路径。

我还看到在空格之前添加 ^ 可能会有所帮助,例如

"""C:\Users\Claire^ Watson\anaconda3\python.exe"""  

或者

"C:\Users\Claire^ Watson\anaconda3\python.exe"  

结果是命令提示符说 C:\Users\Claire: can't open file 'Watson\anaconda3\python.exe: [Errno 2] No such file or directory。

我也尝试删除一些引号,但随后它指出存在语法错误或找不到路径。

我的代码:

Dim objShell As Object
Dim pythonexe As String
Dim pythonscript As String
Dim Username As String

Set objShell = VBA.CreateObject("Wscript.Shell")

Username = "Some name with or without spaces" 'dependent on the user input

pythonscript = """C:\Users\" & Username & "\........py"""

If InStr(Username, " ") > 0 Then ' Checks to see if there are spaces in username

    pythonexe = """C:\Users\" & Username & "\anaconda3\python.exe"""
    
    objShell.Run "cmd /k" & " " & pythonexe & " " & pythonscript
Else

     pythonexe = "C:\Users\" & Username & "\anaconda3\python.exe"
    
     objShell.Run "cmd /k" & " " & pythonexe & " " & pythonscript   ' This section gives no errors
     
End If

标签: pythonexcelvbapathspaces

解决方案


cmd.exe 有非常讨厌的引用规则。但是,您应该能够同时引用 Python 解释器路径和脚本,以便无论用户名中是否有空格,它都能始终如一地工作。尝试这样的事情:

Dim objShell As Object
Dim pythonexe As String
Dim pythonscript As String
Dim Username As String
Dim cmd As String
'Double-quote character
Dim dq As String: dq = Chr(34)

Set objShell = VBA.CreateObject("Wscript.Shell")

Username = "Some name with or without spaces" 'dependent on the user input

pythonexe = dq & "C:\Users\" & Username & "\anaconda3\python.exe" & dq
pythonscript = dq & "C:\Users\" & Username & "\........py" & dq

cmd = "cmd /k " & dq & pythonexe & " " & pythonscript & dq
Debug.Print "Running command (" & cmd & ")"
objShell.Run cmd

正确引用的命令应如下所示(调试行将其打印到即时窗口以进行调试):

cmd /k ""C:\Users\Claire Watson\anaconda3\python.exe" "C:\Users\Claire Watson\.........py""

推荐阅读