Windows CMD设置嵌入式Python解释器PYTHONPATH无效问题咨询
嵌入式Python解释器下PYTHONPATH设置无效的问题解决
问题场景
通过Windows批处理运行自动化Python脚本,嵌入式Python已复制到%userprofile%,批处理代码如下:
pushd "\\Share\Share Drive\share place" set oldir=%cd% cd "%userprofile%\python311" set PYTHONPATH="%userprofile%\python311";"%userprofile%\python311\Lib";"%oldir%" call python "%oldir%\scripts_prd\%script_name%.py" %1 "%ori%"
运行后脚本可执行,但%oldir%目录下的模块无法导入,提示“Module not found”,PYTHONPATH设置未生效。
排查过程
更新1
删除call语句后,打印sys.path发现PYTHONPATH指定的%oldir%未出现在搜索路径中:
%userprofile%\python311\python311.zip; %userprofile%\python311; %userprofile%\AppData\Roaming\Python\Python311\site-packages; %userprofile%\python311\Lib\site-packages; %userprofile%\python311\Lib\site-packages\win32; %userprofile%\python311\Lib\site-packages\win32\lib; %userprofile%\python311\Lib\site-packages\Pythonwin
临时方案是在脚本中添加sys.path.append(os.getcwd()),但希望找到更优解。
更新2
修改批处理变量赋值写法为set "oldir=%cd%"和set PYTHONPATH="%userprofile%\python311;%userprofile%\python311\Lib;%oldir%",该写法在标准安装版Python中有效,但嵌入式解释器仍不生效。
最终解决方案
嵌入式Python解释器默认不会加载site模块,因此会忽略PYTHONPATH环境变量。解决方法如下:
- 打开
%userprofile%\python311目录下的python._pth文件 - 在文件末尾添加一行:
import site - 保存文件后重新运行批处理
添加import site后,嵌入式Python会加载site模块,此时PYTHONPATH的设置会被正常读取,%oldir%下的模块即可成功导入。
内容的提问来源于stack exchange,提问作者hirobank
相关产品推荐
相关产品推荐

