Подвернулось интересное задание, и мне захотелось попробовать свои силы и подучиться.
Задача следующая:
- забросить данные в маткад
- посчитать по формулам из маткадоского файла ответ (открытая математика)
- получить ответ
Для решения я вытащил через PythonWin - COM makepy utility библиотеку “Mathcad Automation API”,
подключил ее к проекту, но столкнулся с проблемой: “что делать дальше?”.
Для примера взял код из официальной документации на VisualBasic:
Public Class Form1
Inherits System.Windows.Forms.Form
'Dimension Objects using Intellisense
Dim MC As Mathcad.Application
Dim WK As Mathcad.Worksheets
Dim WS As Mathcad.Worksheet
#Region “ Windows Form Designer generated code ”#End Region
Private Sub ExitButton(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
'The Cleanup subroutine (see below) closes the application objects in the
'.NET Environment and releases the memory taken up by the Mathcad executable
'Cleanup() is called only if a process was started, and only on exiting the application
If IsNothing(MC) = False Then
Cleanup()
End If
End Sub
Private Sub CalculateButton(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
'Dimension the force and file path variables used in the script
Dim Load As Integer
Dim Path As String
'Extract the path to the Mathcad file from the first text box (MathcadPath)
Path = MathcadPath.Text
'Create the Mathcad application object if one does not already exist
If IsNothing(MC) = True Then
MC = CreateObject("Mathcad.Application")
'Open the Mathcad sheet found at the specified path. If the sheet is not found,
'trap the error and return a message stating that it could not be found. Allow
'the user to update the path by returning focus to the App.
Err.Number = 0
On Error Resume Next
WK = MC.Worksheets
WS = WK.Open(Path)
If Err.Number <> 0 Then
MsgBox("File not found!")
Exit Sub
End If
On Error GoTo 0
End If
'Assign the input value from the combobox (InputLoad) to the variable Load
Load = InputLoad.SelectedItem
'Note that Load is currently cast as an integer.
'Pass Load to the Mathcad sheet where it is bound to a Mathcad variable called F
WS.SetValue("F", Load)
'Extract the variable Smax from the Mathcad sheet, treat it as a string, and place
'it in the third text box (MaxStress), now enabled on the form
MaxStress.Enabled = True
MaxStress.Text = WS.GetValue("Smax").AsString
End Sub
Sub Cleanup()
'Close the Mathcad application running in the background and do not prompt to save
'changes
WS.Close(Mathcad.MCSaveOption.mcDiscardChanges)
System.Runtime.InteropServices.Marshal.ReleaseComObject(WK)
System.Runtime.InteropServices.Marshal.ReleaseComObject(WS)
System.Runtime.InteropServices.Marshal.ReleaseComObject(MC)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Populate the combobox with the desired loads available to the user
InputLoad.Items.Add("10")
InputLoad.Items.Add("15")
InputLoad.Items.Add("20")
InputLoad.Items.Add("25")
InputLoad.Items.Add("30")
'The values of items could also be calculated, based on the index, or
'this could be a free entry text box, requiring error checking and
'type conversion.
'ComboBox defaults to the first item on the list, 10
'Units are added in the Mathcad worksheet - they cannot be passed here
'The combobox defaults to its first entry
InputLoad.SelectedIndex = 0
End Sub
End Class[/quote]
Попробовал сделать что-то похожее, уже на этапе вызова маткада и создания рабочего пространства столкнулся с проблемой:
[quote]Traceback (most recent call last):
File "J:\MathPlan\src\main.py", line 5, in <module>
mc = mathLib.IMathcadApplication()
File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 420, in __init__
oobj = pythoncom.new(self.CLSID)
pywintypes.com_error: (-2147221164, '\xca\xeb\xe0\xf1\xf1 \xed\xe5 \xe7\xe0\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe8\xf0\xee\xe2\xe0\xed', None, None)[/quote]
[code]import mathLib
testFile = "test.mcd"
mc = mathLib.IMathcadApplication()
wk = mathLib.IMathcadWorksheets(mc)
ws = mathLib.IMathcadWorksheet(wk.Open(testFile))[/code]
Маткадоская библиотека (http://rghost.net/8846071).
Для её работы потребуется win32com (http://sourceforge.net/projects/pywin32/).
Что я сделал не так?
Помогите решить, пожалуйста.