gpt4 book ai didi

python - 使用一个 C 程序运行 python 脚本(不同的 python 版本)

转载 作者:行者123 更新时间:2023-11-30 16:47:13 26 4
gpt4 key购买 nike

我想在一个小型 C/++ 程序的线程中运行一些 python 脚本,但我需要不同的 python 版本来运行这些脚本,因为 MySQLdb 包在 python3 中不起作用,并且某些包不可用在Python2中。

#include <stdio.h>
#include <python2.7/Python.h>
#include <python3/Python.h>

void main(int argc, char *argv[])
{
FILE* file;

Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
file = fopen("myscript.py","r");
PyRun_SimpleFile(file, "myscript.py");
Py_Finalize();

return;
}

或通过

system ("python2.7 myscript1.py arg1 arg2");
system ("python3 myscript2.py arg1 arg2");

您有什么想法或其他方法来解决我的问题吗?

最佳答案

您可以使用system()调用来执行Python脚本,但无需在命令行上指定Python可执行文件的版本。

您可以使用shebang。

使用 #!/usr/bin/python3 作为要使用 python3#!/usr/bin 运行的脚本的第一行/python2 在您想要使用 python2 运行的脚本中。

如果您在 Windows 上工作,请查看 python launcher

关于python - 使用一个 C 程序运行 python 脚本(不同的 python 版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43410292/

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