gpt4 book ai didi

python - 通过 std::system 调用 python 时出错

转载 作者:行者123 更新时间:2023-12-03 03:29:53 25 4
gpt4 key购买 nike

当我尝试使用以下方法在 C++ 中调用 python 时:

QString command = "cd C:\\python\\python37 && python C:\\projects\\file_editor.py" 
QByteArray ba = command.toLocal8Bit();
const char *c_str2 = ba.data();
std::system(c_str2)

我收到此错误:

Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

有什么想法可以解决这个问题吗?

编辑:我的 PATH 变量中的 python 相关路径是:

C:\python\python37\Scripts

我可以使用 Qt我也尝试过这个:

QProcess process;
QStringList pythonCommandArguments = QStringList() << "C:\\projects\\file_editor.py"
process.start("python", pythonCommandArguments);

但随后我收到此错误:

QProcess: Destroyed while process ("python") is still running.

最佳答案

无需cd进入python解释器的目录。

另一方面,许多项目(如果编码不好)可能需要您 cd 进入项目目录。

如果编码良好,则根本不需要 cd

我还会使用 py.exe 包装器,它安装在 Windows 下,旨在选择正确的可执行文件,也可能会处理一些环境变量。如果您安装了多个 python 版本,我可以向您展示如何使用 py.exe 选择正确的版本。

尝试以下两个选项:

QString command = "py.exe C:\\projects\\file_editor.py"
QString command = "cd C:\\projects && py.exe C:\\projects\\file_editor.py"

如果遇到编码问题,请设置环境变量PYTHONIOENCODINGputenv() 为您想要的编码'utf-8'/'cp1252' 或任何你喜欢的。

我建议您首先从 cmd 行尝试,只有当您从那里开始工作时,您才可以从 C++ 尝试

示例:

cd c:\projects
echo just some_text > stdin.txt
set PYTHONIOENCODING=cp1252
type stdin.txt | py.exe C:\projects\file_editor.py

我使用类型 stdin.txt | py.exe ... 技巧,这样我就可以模拟调用 python,而无需连接到控制台。

我没有安装C++的Windows PC,所以无法测试。但希望这(使用 py.exe 并明确设置 PYTHONIOENCODING)能让您走上正确的轨道

关于python - 通过 std::system 调用 python 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58937430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com