简体   繁体   English

在Excel中将Python脚本作为可执行文件调用

[英]Calling Python script in excel as executable

I am currently developing a tool for a client that interfaces with both python 2.7 and excel 2013 and as a result running into a problem. 我目前正在为与python 2.7和excel 2013交互的客户端开发工具,结果遇到了问题。

As background, I have a python code I want to run as a executable. 作为背景,我有一个要作为可执行文件运行的python代码。 The client doesn't have python on their computers so it's vital that the exe runs without .py. 客户端的计算机上没有python,因此exe文件无需.py即可运行非常重要。 I've converted the script from a .py to a .exe with py2exe. 我已经使用py2exe将脚本从.py转换为.exe。 Then I am trying to call that .exe with VBA. 然后,我试图用VBA调用该.exe。 When the macro runs it looks like it pulls up the command prompt for a second but it doesn't run the .exe. 宏运行时,看起来好像拉起了命令提示符一秒钟,但它没有运行.exe。 When I go into the directory and double click the .exe however, it runs fine and outputs what I want it to. 当我进入目录并双击.exe时,它运行良好并输出我想要的文件。

Below is my code in VBA: 下面是我在VBA中的代码:

Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
ChDir folderPath

Dim stAppName As String
stAppName = folderPath & "\dist\MAT.exe"
Call Shell(stAppName, 1)

Not sure if my Shell needs any other inputs 不确定我的外壳是否需要其他输入

Any help would be appreciated! 任何帮助,将不胜感激!

this is an indirect answer more to help you figure out what might be wrong 这是一个间接答案,可以帮助您找出可能出问题的地方

in your main file put your program in a main function (you dont have to call it main... you can call it whatever) 在您的主文件中,将您的程序放入一个main函数中(您不必将其命名为main ...您可以随便调用它)

def main():
   #do whatever

then when you run it if its main do this 那么当您运行它时,如果它主要这样做

if __name__ == "__main__":
    try:
       main()
    finally:
       raw_input("Hit enter To Close...")

this will guarantee your window to stay open even if there is an uncaught error 即使出现未捕获的错误,这也将确保您的窗口保持打开状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM