【Batch Job】Batch Job中执行一段Python代码,遇见Failure Exit Code
问题描述
在Azure Batch Job中执行一段Python代码,遇见Failure Exit Code。
print("start mian.py") if __name__ =="__main__": print("__main__")
就算只使用一个简单的 print 方法,也是出现Failure Exit Code错误。
进一步在Batch Job的 stderr 日志中,发现了错误消息:
Traceback (most recent call last): File "site-packages\PyInstaller\loader\rthooks\pyi_rth_win32comgenpy.py", line 49, in <module> File "c:\hostedtoolcache\windows\python\3.7.9\x64\lib\site-packages\PyInstalle r\loader\pyimod03_importers.py", line 623, in exec_module File "site-packages\win32com\__init__.py", line 8, in <module> File "c:\hostedtoolcache\windows\python\3.7.9\x64\lib\site-packages\PyInstalle r\loader\pyimod03_importers.py", line 623, in exec_module File "site-packages\pythoncom.py", line 2, in <module> File "c:\hostedtoolcache\windows\python\3.7.9\x64\lib\site-packages\PyInstalle r\loader\pyimod03_importers.py", line 623, in exec_module File "site-packages\win32\lib\pywintypes.py", line 126, in <module> File "site-packages\win32\lib\pywintypes.py", line 116, in __import_pywin32_sy stem_module__ ImportError: DLL load failed: The specified module could not be found. [2504] Failed to execute script pyi_rth_win32comgenpy
问题解答
首先,出现 Failure Exit Code 表示Batch Job已经开始执行,但是在运行脚本或者执行文件中,出现了异常导致Job退出 Exit with 1 (正常的退出code 为 Exit code 0)。而本次错误中的异常为 “ DLL load failed: The specified module could not be found.”。缺少Python代码的可执行环境。
因为Batch Job中执行的文件是通过PyInstaller把python code打包为一个main.exe可执行文件,这样在没有预先安装Python runtime的环境中,也可以执行Python代码。所以需要研究 PyInstaller 在打包时,是否没有包含Python Runtime文件。
参考资料
ImportError: DLL load failed while importing win32api: The specified procedure could not be found. [25960] Failed to execute script pyi_rth_win32comgenpy : https://github.com/mhammond/pywin32/issues/1791
python - Failed to execute script pyi_rth_win32comgenpy after packing with pyinstaller : https://stackoverflow.com/questions/65587443/failed-to-execute-script-pyi-rth-win32comgenpy-after-packing-with-pyinstaller
added
--hidden-import "pywin32"
to the pyinstaller command, and it worked!
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!