简体   繁体   English

我可以用python编写我的应用程序,然后从C运行它们吗?

[英]Can I write my apps in python and then run them from C?

I need to write a client-server application. 我需要编写一个客户端服务器应用程序。 I want to write it in python, because I'm familiar with it, but I would like to know if the python code can be ran from C. I'm planning to have two C projects, one containing the server code, and one containing the client code. 我想用python编写它,因为我对此很熟悉,但是我想知道python代码是否可以从C运行。我计划有两个C项目,一个包含服务器代码,另一个包含客户端代码。

Is it possible to eval the python code and run it ? 可以评估python代码并运行它吗? Is there another way of doing this? 还有另一种方法吗?

The bottom line is that the python code must run from C, and it must behave exactly as if ran under the python interpreter. 底线是python代码必须从C运行,并且其行为必须完全像在python解释器下运行一样。 I'm asking this now, because I don't want to waste time writing the python code just to find out later that I can't achieve this . 我现在问这个问题,是因为我不想浪费时间编写python代码,只是以后才发现我无法实现这一点。 As a sidenote, I only plan on using basic python modules ( socket,select, etc. ). 附带说明一下,我只打算使用基本的python模块(socket,select等)。

EDIT: maybe this edit is in order. 编辑:也许此编辑是有序的。 I haven't embedded python in C before, and I don't know what the behaviour will be. 我以前没有在C中嵌入python,而且不知道行为会是什么。 The thing is, the server will have a select loop, and will therefore run "forever". 问题是,服务器将有一个选择循环,因此将“永远”运行。 Will C let me do that ? C可以让我这样做吗?

EDIT2: here is why I need to do this. EDIT2:这就是为什么我需要这样做。 At school, a teacher asked us to do a pretty complex client-server app in C. I'm going to cheat, write the code in python and embed it in C. 在学校里,一位老师要求我们用C语言编写一个非常复杂的客户端-服务器应用程序。我要作弊,用python编写代码并将其嵌入到C语言中。

这是一个很好的教程,可以准确地做到这一点http://www.linuxjournal.com/article/8497

It's called embedding Python -- it's well covered in the Python docs. 这称为嵌入Python-Python文档中对此进行了很好的介绍。 See https://docs.python.org/extending/embedding.html 参见https://docs.python.org/extending/embedding.html

See how do i use python libraries in C++? 看看如何在C ++中使用python库?

Yes you can run the Python code from C by embedding the interpreter in your program. 是的,您可以通过将解释器嵌入程序来从C运行Python代码。 You can expose portions of your C code to Python and call your exposed C code from Python as if they were normal Python functions. 您可以将C代码的一部分公开给Python,并从Python调用公开的C代码,就像它们是普通的Python函数一样。

A good start is the Embedding section in the Python docs. 一个好的开始是Python文档中的“ 嵌入”部分。 Also have a look at the article linked to by cobbal. 也可以看看cobbal 链接文章

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

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