【问题标题】:Run python scripts (different python verions) with one C program使用一个 C 程序运行 python 脚本(不同的 python 版本)
【发布时间】:2017-09-10 15:21:37
【问题描述】:

我想用一个小的 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");

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

【问题讨论】:

    标签: python c++ c python-2.7 python-3.x


    【解决方案1】:

    您可以使用system() 调用来执行您的python 脚本,但不需要在命令行中指定python 可执行文件的版本。

    你可以使用shebang。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2016-09-03
      • 1970-01-01
      相关资源
      最近更新 更多