社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

为什么VB外壳函数不停止Python代码执行窗口?

PCG • 3 年前 • 1171 次点击  

使用excel VB Shell函数执行python代码不会在python指令处停止。它可以快速打开和关闭,但不显示Python指令。以下excel宏运行python代码:

Sub run_python()
    
    python_exe = "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe"
    python_script = "C:/Users/Goerge/OneDrive - MS Corporation/Documents/Development/python-excel/excel_python.py"
    
    If Dir(python_exe) = "" Then
    MsgBox ("Python executable does not exists")
    End If
    
    If Dir(python_script) = "" Then
    MsgBox ("Python script does not exists")
    End If
    
    python_code = python_exe & " " & " -k " & python_script
    
    RetVal = Shell(python_code)
    
End Sub

python代码示例:

import os
    
print("This is first python function called in excel")
for x in range(0,9999999999999999999):
    print("Counting : ", x)
    #input('Press ENTER to exit')
os.system("pause")

我在这里添加了几个步骤(用于循环和“暂停”)来保持代码的执行,但在通过宏执行时它不会响应。然而,当直接在VS代码中运行时,该代码可以正常工作。

我做错了什么?

我使用的是Excel 365和Python 3.7。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130835
 
1171 次点击  
文章 [ 1 ]  |  最新文章 3 年前
PCG
Reply   •   1 楼
PCG    3 年前

该问题与路径中的空间有关。python路径中的空格可以,但是python脚本路径不应该有任何空格。当有空格时,它会被分解成单独的变量,并且永远不会将脚本视为文件。因此,解决方法是对带有空格的路径使用双引号。

VB脚本应如下所示:

Sub run_python()

python_exe = "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe"
python_script = "C:/Users/Goerge/OneDrive - MS Corporation/Documents/Development/python-excel/excel_python.py"

If Dir(python_exe) = "" Then
    MsgBox ("Python executabl does not exists")
End If

If Dir(python_script) = "" Then
    MsgBox ("Python script does not exists")
End If

python_code = python_exe & " " & """" & python_script & """"
MsgBox python_code
RetVal = Shell(python_code)

'Shell "pskill " & " " & RetVal

End Sub