如何阻止Py_Initialise崩溃应用程序?

时间:2011-09-27 06:26:21

标签: c++ python excel vba vb6

从VBA和VB6我调用一个DLL创建一个Python解释器。如果我将PATH环境变量设置为指向"C:\python27"而将PYTHONPATH设置为"c:\python27\lib"则一切正常。

如果我未设置PATH,则调用Py_Initialise()会崩溃XL或我的VB6应用,即使我先使用Py_SetProgramName致电"c:\python27\python27.exe"

我想在VB / VBA中指定安装而不是在环境中设置,因为我在XL中无法做到这一点(适用于VB6)。

3 个答案:

答案 0 :(得分:3)

到目前为止,我发现的最佳答案是它是Python中的一个错误 - http://bugs.python.org/issue6498。解释器似乎在某些错误上调用exit()而不是将代码传递给调用者。如果你在一个应用程序中嵌入python,不是很友好。但是你去了。

答案 1 :(得分:1)

尝试在调用dll之前更改工作目录:

在您的VBA代码中:

chdir("c:\python27\") '- change the working-directory for python
=> call dll '- call the dll
chdir(app.Path) '- change back to your folder (maybe you want to save your current folder bevore you change it the first time and change back to this?!)

托马斯

答案 2 :(得分:0)

您只需检查是否设置了所需的环境变量:

dim PPath as string
PPath = trim(Environ("PYTHONPATH"))
if (PPath<>"")
  <call dll>
else
  msgbox ("Error!")
end if

或者你可以在另一个测试过程中运行dll:如果这个调用工作你知道调用dll是可以的 - 这取决于你使用的DLL调用所以我不确定:

Private Declare Function CloseHandle Lib "kernel32" (ByVal _
    hObject As Long) As Long

Private Declare Function OpenProcess Lib "kernel32" (ByVal _
    dwDesiredAccess As Long, ByVal bInheritHandle As _
    Long, ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" _
    (ByVal hProcess As Long, lpExitCode As Long) As Long

Const STILL_ACTIVE = &H103
Const PROCESS_ALL_ACCESS = &H1F0FFF

...
dim IsActive as boolean
dim Handle as long
Dim TaskID As Long
TaskID = Shell("rundll32.exe pyton.dll Py_Initialise()", vbNormalNoFocus)

<wait for some time>

'- check if pyton.dll is still running
Handle = OpenProcess(PROCESS_ALL_ACCESS, False, TaskID)
Call GetExitCodeProcess(Handle, ExitCode)
Call CloseHandle(Handle)

IsActive = IIf(ExitCode = STILL_ACTIVE, True, False)

if (not IsActive) then
  msgbox ("Error!")
else
  <kill process>
  <call dll normally>
end if

关心托马斯