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.
问题是vba中的shell()在其默认文件夹中启动cmd.exe,而不是在当前工作簿的活动文件夹中。在我的python脚本中,我有相对路径引用,这是一个问题。为了解决这个问题,我在python脚本中使用os模块在开始时更改当前目录。
1 个解决方案
#1
2
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)实用程序可以显示正在运行的进程的所有环境设置。
#1
2
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)实用程序可以显示正在运行的进程的所有环境设置。