[英]Compiling C++ code using Python interpreter running under windows shell
My environment is: 我的环境是:
Windows 7. PyDev IDE (eclipse). Windows7。PyDevIDE(蚀)。 Python 2.7. Python 2.7。
I want to compile and test some code I write in C++ (in the future, this code will be generated by a Python script). 我想编译和测试一些用C ++编写的代码(将来,此代码将由Python脚本生成)。 I need to get to compile a simple .c file for being used as a python extension. 我需要编译一个简单的.c文件以用作python扩展名。
Right now my code is: 现在我的代码是:
/*
file: test.c
This is a test file for add operations.
*/
float my_add(float a, float b)
{
float res;
res = a + b;
return res;
}
And the .py file: 和.py文件:
import subprocess as sp
import os
class PyCompiler():
def __init__(self, name):
self.file = name
self.init_command = r"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
self.compiler_command = r"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\cl.exe"
sp.call(self.init_command + " " + self.file)
def compile(self):
alfa = sp.call(self.compiler_command)
print(alfa)
TestCode = PyCompiler(r"C:\Python27\CodeGenerator\src\nested\test.c")
TestCode.compile()
If I launch this script, I get: 如果启动此脚本,则会得到:
Which means I got an error in the method PyCompiler.compile, since the return of subprocess.call is not 1. 这意味着我在方法PyCompiler.compile中出错,因为subprocess.call的返回不是1。
Can you provide some guidance on this issue? 您可以提供有关此问题的一些指导吗?
Do you know any other way of doing this? 您知道其他方式吗?
I actually managed to solve the problem by installing MinGW and using it to compile my C code. 通过安装MinGW并使用其编译我的C代码,我实际上设法解决了该问题。 My python code for this is: 我为此的python代码是:
import subprocess as sp
import os
import importlib
my_env = os.environ
Class init: 类初始化:
class PyCompiler():
def __init__(self, name_in, module, dep_list):
self.file = name_in
self.dep = dep_list
self.module_name = module
self.compiler_command = r"python setup.py build_ext --inplace -c mingw32 "
''' Here it goes the creation of the setup.py file: '''
self.set_setup()
And class methods: 和类方法:
def compile(self):
command = self.compiler_command
self.console = sp.call(command, env=my_env)
def include(self):
module = __import__(self.module_name)
return module
def set_setup(self):
dependencies = ""
for elem in self.dep:
dependencies = dependencies + ",'"+elem+".c'"
filename = "setup.py"
target = open (filename, 'w')
line1 = "from distutils.core import setup, Extension"
line2 = "\n"
line3 = "module1 = Extension('"
line4 = self.module_name
line5 = "', sources = ['"+self.file+"'"+dependencies+"])\n"
line6 = "setup (name = 'PackageName',"
line7 = "version = '1.0',"
line8 = "description = 'This is the code generated package.',"
line9 = "ext_modules = [module1])"
target.write(line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9)
target.close()
And the execution code: 和执行代码:
TestCode = PyCompiler(file, module, [lib])
TestCode.compile()
test = TestCode.include()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.