来自Excel VBA的Shell调用冻结 - 涉及MacScript和Python(Excel for Mac 2011)

时间:2014-07-28 15:42:39

标签: python excel macos vba excel-vba

此宏在Excel 2011 for Mac上正常运行:

Sub Works()
    scriptToRun = "do shell script ""/anaconda/bin/python -c "" & quoted form of ""import test_file"" "
    res = MacScript(scriptToRun)
    Debug.Print res
End Sub

相应的test_file.py文件(放在python路径上的某个地方)是:

import sys
print(sys.version)

然而,当我涉及appscript Python包时,它会冻结很长时间而且什么都不做。将test_file.py文件更改为此(pip install appscript优先):

import appscript
app = appscript.app('Microsoft Excel')
app.cells['A1'].value.set(2)

但是,当我直接从AppleScript编辑器运行命令时,这可以工作:

do shell script "/anaconda/bin/python -c " & quoted form of "import test_file"

如何从Mac上的Excel VBA调用此功能? (顺便说一下,在Windows上,它可以轻松地与WScript.Shellpywin32

一起使用

1 个答案:

答案 0 :(得分:0)

解决方法是使用此answer中的system()/popen()调用,并将命令作为后台进程运行,最后带有&符号:

Private Declare Function system Lib "libc.dylib" (ByVal command As String) As Long

Sub RunTest()
    Dim result As String
    result = system("/anaconda/bin/python -c 'import test_file' &")
End Sub