我的环境是:
Windows 7。 PyDev IDE(eclipse)。 Python 2.7。
我想编译和测试一些我用C ++编写的代码(将来,这段代码将由Python脚本生成)。我需要编译一个简单的.c文件,用作python扩展。
现在我的代码是:
/*
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;
}
.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()
如果我启动此脚本,我会得到:
这意味着我在方法PyCompiler.compile中出错,因为subprocess.call的返回不是1.
您能就此问题提供一些指导吗?
你知道其他任何做法吗?
答案 0 :(得分:0)
我实际上设法通过安装MinGW并使用它来编译我的C代码来解决问题。我的python代码是:
import subprocess as sp
import os
import importlib
my_env = os.environ
班级初学者:
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()
和班级方法:
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()
执行代码:
TestCode = PyCompiler(file, module, [lib])
TestCode.compile()
test = TestCode.include()