vba 使用Shell从excel vba运行python脚本什么都不做
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12584195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running python script from excel vba using Shell does nothing
提问by Dan
I am trying to run a python script in excel VBA like this:
我正在尝试在 excel VBA 中运行一个 python 脚本,如下所示:
Shell("python " & ActiveWorkbook.Path & "\CreateVolsurface.py -d ""10 Sep 12""")
but it does nothing. If I watch the task manager, a python process doesn't even get created. If I debug and copy the string created in the code above and paste it into command prompt it runs perfectly.
但它什么也不做。如果我查看任务管理器,甚至不会创建 python 进程。如果我调试并复制在上面的代码中创建的字符串并将其粘贴到命令提示符中,它将完美运行。
The python script takes a date (as a string) as a parameter and creates an image file.
python 脚本将日期(作为字符串)作为参数并创建图像文件。
Any idea why this would not work or how I could debug it?
知道为什么这不起作用或我如何调试它吗?
I've also tried this:
我也试过这个:
Shell ("python CreateVolsurface.py -d ""10 Sep 12""")
and this:
和这个:
ret_val = Shell("python " & ActiveWorkbook.Path & "\CreateVolsurface.py -d ""10 Sep 12""", vbHide)
but they also do nothing.
但他们也无所作为。
The issue was that shell()
in vba starts cmd.exe in it's default folder and not in the active folder of the current workbook. In my python script I had relative path references which was an issue. To solve this I used the os module in my python script to change the current directory at the start.
问题是shell()
在 vba 中启动 cmd.exe 是在它的默认文件夹中,而不是在当前工作簿的活动文件夹中。在我的 python 脚本中,我有相对路径引用,这是一个问题。为了解决这个问题,我在 python 脚本中使用了 os 模块来在开始时更改当前目录。
采纳答案by Ryan
Try specifying the path to python.exe, or you may need to add the path to your %PATH% environment variable.
尝试指定 python.exe 的路径,或者您可能需要将路径添加到 %PATH% 环境变量。
Try the following to verify Shell is working and step through with the debugger:
尝试以下操作以验证 Shell 是否正常工作并逐步调试调试器:
ret_val = Shell("notepad.exe", vbNormalFocus)
If that works, then you should try specifying the path:
如果可行,那么您应该尝试指定路径:
args = ActiveWorkbook.Path & "\CreateVolsurface.py -d ""10 Sep 12"""
ret_val = Shell("C:\python27\python.exe " & args)
If you need to check if python is in your %PATH% environment variable, the Process Explorer (procexp.exe) utility from sysinternals can show you all of the environment settings for a running process.
如果您需要检查 python 是否在 %PATH% 环境变量中,sysinternals 的 Process Explorer (procexp.exe) 实用程序可以向您显示正在运行的进程的所有环境设置。