【发布时间】:2020-10-10 08:31:01
【问题描述】:
我正在尝试通过 VBA Excel 打开一个 py 脚本。
该脚本用于与进行有限元分析的工程软件进行交互。该脚本可以直接从 py 编辑器运行。
他们准备了一个 Python 库,我必须在脚本开头导入该库,该库还需要一些密码和登录凭据,以便脚本与该特定软件进行交互。
我可以通过 VBA 中的 Shell 打开简单的 py 脚本(例如经典的 Hello World)。
我准备的脚本比较复杂。当使用 shell 通过 VBA 打开我的脚本时,它会闪烁 cmd 窗口并且没有任何反应。
下面是我在 VBA 中编写的用于打开 Python 解释器和 Python 脚本的子例程,用于说明:它返回错误消息 2。
Sub RunPythonScript()
Dim wsh As Object
Dim PythonExe, PythoScript As String
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
Dim pth As String
PythonExe = """C:\ProgramData\Bentley\Geotechnical\PLAXIS 2D CONNECT Edition V20\python\python.exe"""
PythoScript = """C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py"""
pth = PythonExe & PythoScript
Set wsh = VBA.CreateObject("WScript.Shell")
errorCode = wsh.Run(pth, windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
网上有很多关于如何运行 Python 脚本的信息。
在这个论坛中:How to call python script on excel vba?。我还创建了一个可以通过 VBA 打开的 bat 文件,但是收到以下错误消息:
C:\Users\ukjfv001\Desktop\MyPython>"C:\Users\ukjfv001\Anaconda3\python.exe" ""C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py"" 开始 回溯(最近一次通话最后): 文件“C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py”,第 16 行,在 from plxscripting.easy import * #call Plaxis 脚本库 ModuleNotFoundError: 没有名为“plxscripting”的模块
下面是一些 Python 代码,我必须将其放在 SciTE 编辑器(工程软件随附)中脚本的顶部。
从我在错误消息(上面)和下面来自 plxscripting.easy import 的代码中可以看到,我没有做一些事情。
我是 Python 新手,所以通常我需要实际示例来了解要做什么。
from plxscripting.easy import * #callS engineering scritping library
inputport = 8888888
plaxispw = some_password
plaxis_path = C:\Users\ukjfv001\... #to here the software is intalled
plaxis_input = Plaxis.exe #software executable
if not process_exists(plaxis_input): #checkS if software is alreayd running
# first launch software
args = [os.path.join(plaxis_path, plaxis_input),"--AppServerPort={}".format(inputport),"--AppServerPassWord={}".format(plaxispw)]
inputprocess = subprocess.Popen(args)
# Initialize new_server with waiting time
s_i, g_i = new_server('localhost', inputport, password=plaxispw, timeout=10.0)
s_i.new()#starts a new Project
#after this point is where I have my Python script...```
【问题讨论】:
-
这是一个棘手的问题。我的第一个猜测是 Python 在您的脚本和您手动调用它时从不同的位置运行。尝试将“import sys”和“print(sys.path)”放在 Python 脚本的顶部。
-
然后检查modules path是否在'sys.path'中。
-
我不知道答案,但一个很好的测试方法是将您传递给 wsh.run 的 pth 字符串直接放入您的命令提示符以查看它是否运行/你得到的错误。