pandas 如何通过VBA成功执行Python

oalqel3c  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(101)

这是我正在尝试运行的VBA代码:

Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

PythonExe = """C:\Users\me\AppData\Local\Programs\Python\Python39\python.exe """
PythonScript = """C:\Users\me\test\VBAult\auth.py"""

'Run the Python Script
objShell.Run PythonExe & PythonScript, 0, True

MsgBox "Executed!"

End Sub

这是我的Python代码:

import pandas as pd
from pandas import json_normalize
import requests
import json

url_auth = 'https://api-gateway.com/uaa/oauth/token'

payload_auth = {'grant_type': 'client'} 

username = "username"
password = "password"
  
response_auth = requests.post(url_auth, auth=(username, password), data=payload_auth)
 
data = response_auth.json()

url_f = 'https://api-gateway.com/api/test'

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer '+ data['access_token'],
}

payload_f = json.dumps([
  {
    "operation": "xxxxx",
    "reference": "xxxxx",
    "status": "xxx"
  }
])

response_f = requests.get(url_f, headers=headers, data=payload_f, verify=True)

json_data = json.loads(response_f.text)

df_json_data = pd.json_normalize(json_data)

df_json_data.to_excel('C:\Users\me\Downloads\convertjson.xlsx', index=False)

它进行一些API调用,并在最后将JSON响应转换为Excel文件。当我从我的笔记本执行它时,它工作得很好,但是当我使用上面的代码从VBA执行它时,它什么也不做。只返回msgbox,但不创建我需要的excel文件。
如何通过使VBA和我的Python脚本一起工作来归档我所需要的内容?

8mmmxcuj

8mmmxcuj1#

下面的代码为我工作。下面的代码将在VBA控制台上打印output/error,允许您确定实际问题。

Sub python_script_run()

    pyexe = "C:\thonny\python.exe" 'change to your python executable
    pysc = "D:\_code_\SEM_RENO_V3\sem_reno.py" 'change python script path as required
    
    pth = Left(pysc, InStrRev(pysc, "\") - 1)
    ChDir pth 'chage directory to script
    
    sCmd = pyexe & " " & pysc
    Debug.Print sCmd
    Set objShell = CreateObject("WScript.Shell")
    Set ObjExec = objShell.Exec("cmd.exe /k " & sCmd)
    
    Do
        strFromProc = ObjExec.Stdout.ReadLine()
        Debug.Print strFromProc 'error/output will be printed in vba console
    Loop While Not ObjExec.Stdout.atEndOfStream

End Sub

相关问题