我使用Windows批处理作为用户运行Python脚本来处理一些简单自动化请求的入口。我已经提到了答案。假设我使用另一批将 embedded 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%"
但是,这个
set PYTHONPATH=...
在这里不起作用。该脚本可以访问,但无法访问 %oldir% 中的任何其他模块,报告错误“找不到模块”。
只是想知道 PYTHONPATH 是否应该为 嵌入式 Python 解释器设置不同的方式?
更新1:
感谢蒂姆,我删除了
call
。
我编写了一个包含 print(sys.path)
的脚本,它返回以下值(用户配置文件已替换):
%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
显然
set PYTHONPATH
在这个嵌入式Python解释器中不起作用。
我还展示了
os.getcwd
,它显示了存储Python脚本的网络文件夹,并且可以使用解决方法sys.path.append(os.getcwd())
作为解决方法。但我相信一定有更好的解决方案。
更新2:
感谢莫菲。我已将代码更改为
pushd "\\Share\Share Drive\share place"
set "oldir=%cd%"
...
set PYTHONPATH="%userprofile%\python311;%userprofile%\python311\Lib;%oldir%"
在标准(已安装)Python 解释器中完美运行。但它在嵌入式解释器中仍然不起作用。
但是感谢大家,我已经找到解决方案并将很快更新。
感谢 Tims 和 Mofi,我更新了批处理代码,但发现它对于 嵌入式 Python 仍然没有用处。幸运的是,我找到了原因和解决方案。
结论:嵌入式Python解释器不支持PYTHONPATH。这可以从Python社区的issue28245得到证明。在嵌入式 Python 解释器中使用环境变量是“不可能”的。
解决方案:嵌入式Python解释器中的python[version]._pth
文件。编辑
python311._pth
(这是为了我的解释器)对目录进行硬编码。这适用于本地位置或共享文件夹。请参阅文档。 从技术上讲,我可以对
python311._pth
进行硬编码,并每次使用 Windows 批处理将其复制到嵌入式解释器目录中。例如:
copy python311._pth "%userprofile%\python311"
这对我来说非常有效。