【问题标题】:Is There any exec() function in c as in pythonc 中是否有任何 exec() 函数,如 python 中一样
【发布时间】:2021-04-21 04:37:09
【问题描述】:

这是执行外部 python 文件的 Python 代码

exec(open("file.py").read())

如何在c中做到这一点

【问题讨论】:

  • 顺便提一下,这并不是在python中执行其他python文件的最佳方式。
  • 你如何想象这在细节上工作?由于 C 是一种编译语言,它应该运行编译后的工件、编译代码还是解释源代码?
  • “这是执行外部 python 文件的 Python 代码”这通常不是在 Python 中所做的。你到底想完成什么?

标签: python c


【解决方案1】:

ma​​in.cpp

#include <iostream>
#include <string>
#include <list>

class PrivateDriverData {
    public:
        std::string PythonExecutable = "python3";
        std::string exec(std::string command) {
            char buffer[128];
            std::string result = "";
            // Open pipe to file
            FILE* pipe = popen(command.c_str(), "r");
            if (!pipe) {
                return "popen failed!";
            }
            while (!feof(pipe)) {
                if (fgets(buffer, 128, pipe) != NULL)
                    result += buffer;
            }
            pclose(pipe);
            return result;
        }
};

std::string ExecDriver() {

    PrivateDriverData LocalPDD;
    
    std::string ScraperExecuteData = LocalPDD.PythonExecutable + " file.py";

    return LocalPDD.exec(ScraperExecuteData);
}

int main() {
    std::string answer = ExecDriver();
    std::cout << answer << "\n";
}

【讨论】:

    【解决方案2】:

    C 的壁橱里的东西是 dlopen()。它打开一个编译和链接的动态库,并提供一种运行它包含的代码的方法。

    它不是标准 C 语言,需要托管环境,因此无法在 Arduino 等设备上运行。

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 2019-04-12
      • 1970-01-01
      • 2013-03-23
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2013-04-02
      相关资源
      最近更新 更多