我想學習如何從 C 代碼中執行 Python 程式。這是如何完成的,例如使用如下所示的最簡單的 C 和 Python 程式(經典的“Hello World”程式)?現在我想學習如何在我的 Windows 10 桌面上執行此操作,我有 Visual Studio 并且可以編碼和執行 C/C /Python;一個長期目標是在 Raspberry Pi 上做這種事情。非常感謝任何幫助。我的 Windows 10 PC 上安裝了 Python 3。
// C Program
#include <iostream>
int main() {
std::cout << "Hello World!";
// How can the above line of code be changed so that
// 'Hello World!' is output using a call to a simple
// hello.py program ?
return 0;
}
uj5u.com熱心網友回復:
在 Visual Studio 中,您需要確保相關的 Python 包含目錄和庫鏈接到您的 C 專案。首先,找到你的系統上安裝了 Python 的位置;對我來說它在里面,C:\Python39但如果 Windows 決定將它埋在其他地方,你可能不得不進行一些瘋狂的追逐。
確保您的目標架構與 Python 架構相匹配;這幾乎肯定意味著確保將友好的大Local Windows Debugger按鈕旁邊的下拉選單設定為x64。
接下來,在您的 Visual Studio 專案中,假設它名為PythonTestProject,您需要在解決方案資源管理器視窗中右鍵單擊專案名稱,然后單擊屬性。然后導航到Configuration Properties -> C/C -> General該目錄并將其添加C:\Python39\include到該Addition include directories欄位,當然將路徑前綴更改為您安裝的位置。然后導航到該欄位Configuration Properties -> Linker -> Input并在其前面添加C:\Python39\libs\python3.lib;(注意分號)Additional dependencies。您的專案現在可以在 Python 上運行了。
要運行一個簡單的檔案,您需要PyRun_SimpleFile在Python.h. 您還需要在呼叫此函式之前初始化解釋器,并可選擇在之后對其進行清理,盡管這將在您的程式結束時自動完成。所以像這樣:
#include <Python.h>
#include <stdio.h>
int main()
{
// Initialize the Python interpreter
Py_Initialize();
// Open a script and run it
const char* filename = "hello.py";
FILE* f = fopen(filename, "rb");
PyRun_SimpleFile(f, filename);
// Clean up any memory and state allocated by the Python interpreter
fclose(f);
Py_Finalize();
}
應該做的伎倆。確保它hello.py與專案中的其余源檔案位于同一目錄中,點擊那個友好的除錯按鈕,它應該會運行你的檔案。
希望這能讓你走上正軌:)。我強烈建議您查看 C 庫,例如pybind11,這將使您的生活比直接處理 C API 容易得多(多得多)。不過,如果你只想做這樣簡單的事情,那么麻煩就不值得了;C API 檔案中描述的函式可以很容易地完成很多簡單的任務。
uj5u.com熱心網友回復:
在 C/C 上,您可以使用 system 命令來執行任何 shell 命令。這將允許您使用幾乎任何其他語言,包括 Python、Node.js、C#... docs
#include <cstdlib>
int main(){
system("echo hello world");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375363.html
