简体   繁体   English

我可以从 C plus plus 运行 python 脚本吗?

[英]Can I run a python script from C plus plus?

I made a basic C++ script that looks like this.我制作了一个基本的 C++ 脚本,看起来像这样。

#include <iostream>

int main()
{
    std::cout << "Hello World!" << std:endl;
}

I complied this and named that complied file pcpp .我遵守了这个并将该编译的文件命名为pcpp

Next, I made a python script named runcpp .接下来,我制作了一个名为runcpp的 python 脚本。 This looks like this.这看起来像这样。

import os
com = 'sudo stdbuf -oL ./pcpp'
os.system(com)

Then, when I run this python script, I see the "Hello World."然后,当我运行这个 python 脚本时,我看到了“Hello World”。 message, However.消息,但是。 now I want to do something totally opposite.现在我想做一些完全相反的事情。

Let's assume I have a file name ppy.py .假设我有一个文件名ppy.py This has script like this.这有这样的脚本。

print("Hello World!")

Now, I want to print this by running C++ compiler.现在,我想通过运行 C++ 编译器来打印它。 How should I do this?我该怎么做?

If you just intend to run a Python script from C/C++ you could simply use system() to execute the Python script like system("./myscript.py") , which will use the interpreter specified in the shebang.如果您只想从 C/C++ 运行 Python 脚本,您可以简单地使用system()来执行 Python 脚本,例如system("./myscript.py") ,它将使用 shebang 中指定的解释器。 This means say you have the script:这意味着说你有脚本:

#!/usr/bin/python3

print("Hello!");

It will run the script using /usr/bin/python3 as that is specified in the shebang.它将使用 shebang 中指定的/usr/bin/python3运行脚本。 Using system("python3 myscript.py") will use python3 in your shell's PATH .使用system("python3 myscript.py")将在你的 shell 的PATH中使用python3

Alternatively, if you want to execute Python code within your C++ program you can embed the Python interpreter into your program, see https://docs.python.org/3/extending/embedding.html . Alternatively, if you want to execute Python code within your C++ program you can embed the Python interpreter into your program, see https://docs.python.org/3/extending/embedding.html .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM