[英]Python script called from VBA called from Python is not working
I maintain an Excel with macro's that download some data from the internet.我维护一个带有宏的 Excel,它可以从互联网上下载一些数据。 The downloading is done within Python (I will call this Python A), stored intermediately, and picked up by the Excel again.
下载在 Python(我将其称为 Python A)中完成,中间存储,并再次由 Excel 拾取。 This Python flow is triggered by a macro within that Excel.
此 Python 流由 Excel 中的宏触发。 Because I have to do this at specific times I wanted to automatize this by using another Python scheduler.
因为我必须在特定时间执行此操作,所以我想通过使用另一个 Python 调度程序来自动执行此操作。 The scheduler opens a Nothing fancy, did that before, at least so I thought.
调度程序打开了一个没什么花哨的东西,以前做过,至少我是这么认为的。 The problem I am currently facing is that Python A is not running correctly when triggered from Python B. The Excel macro is running fine.
我目前面临的问题是 Python B 触发时 Python A 运行不正常。 Excel 宏运行正常。 I know that because some files are being exported, which is also done within a macro.
我知道这是因为正在导出一些文件,这也是在宏中完成的。
What I have tried so far:到目前为止我已经尝试过:
Code in VBA: VBA 中的代码:
cmdLine = "python ""path_with_spaces_to_file"" "
lngResult = ShellAndWait(cmdLine, 0, vbNormalFocus, AbandonWait)
Code in Python B to call Macro: Python B 中的代码调用宏:
import win32com.client
def func():
filename_excel = r"filename_to_excel_with_spaces.xlsm"
xl = win32com.client.DispatchEx('Excel.Application')
xl.Visible = False
xl.Workbooks.Open(Filename=filename_excel, ReadOnly=1)
sheet = xl.ActiveWorkbook.Sheets("Sheetname")
xl.Application.Run("Macroname")
xl.DisplayAlerts = False
xl.Application.Quit()
How I call this function from the scheduler:我如何从调度程序调用这个 function:
subprocess.run(["python3_location.bat", "-c", 'from python_B_file import func; func()'],
stdout=subprocess.PIPE,
cwd=r"path_to_python_B_file",
universal_newlines=True,
timeout=60)
I see an extra cmd window popping up, but there is no new file downloaded.我看到一个额外的 cmd window 弹出,但没有下载新文件。 I cannot see an error message
我看不到错误消息
Trying out different things, I found out that in the normal namespace the command python
refers to the system defaults Python 2.7 installation, while the Python B is 3.7.尝试不同的东西,我发现在正常命名空间中,命令
python
是指系统默认安装 Python 2.7,而 Python B 是。 Python A code was not Python 3 compatible (something with urllib, easily solved to something working in both Python versions). Python 代码与 Python 3 不兼容(与 urllib 的东西,很容易解决在 Python 版本中工作的东西)。 Calling the Excel macro from Python B changed the namespace somehow, and the
ShellAndWait
command referred to Python 3.7.从 Python B 调用 Excel 宏以某种方式更改了命名空间,并且
ShellAndWait
命令引用了 Python 3.7。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.