使用tox构建含C扩展的Python2.7包时无法定位源码求助
Hey there, let's break down why this is happening and how to fix it quickly.
The root cause here is the changedir={envdir} line in your tox.ini—this tells tox to switch its working directory to the virtual environment folder (like /home/user/helloworld-release/.tox/py27/) when running commands. But your setup.py references HelloWorld.c using a path relative to your project root, so when tox runs setup.py from the virtual env directory, gcc can't find the file.
Here are two solid solutions:
Solution 1: Remove the changedir Configuration (Recommended)
This is the simplest fix. Just delete the changedir={envdir} line from your tox.ini:
[tox] envlist = py27 [testenv] wheel=true basepython=py27: python2.7 deps= pytest numpy commands= {envpython} {toxinidir}/runtests.py --mode=full {posargs:}
Now tox will run all commands from your project root directory, so setup.py can easily locate HelloWorld.c using the relative path you already have.
Solution 2: Use Absolute Paths for C Sources (If You Need changedir)
If you have a reason to keep changedir={envdir}, modify your setup.py to use absolute paths for the C source files. This ensures the path is correct no matter where setup.py is run from:
import os del os.link from setuptools import setup, Extension, find_packages # Get the absolute path of your project root directory project_root = os.path.dirname(os.path.abspath(__file__)) module1 = Extension( '_HelloWorld_py', sources=[os.path.join(project_root, 'HelloWorld.c')], include_dirs=['/usr/lib64/python2.7/site-packages/numpy/core/include/'], extra_compile_args=['-std=c99', '-Wno-error=vla'] ) setup( name='HelloWorld', version='0.1', description='Hello World', package_data={'': ['*.h', '*.c']}, ext_modules=[module1] )
Test the Fix
After making either change, re-run the command:
tox --wheel
Your C extension should compile successfully now, and tox will generate the wheel package as expected.
Quick side note: Your package_data setup is for including files in the final wheel, not for finding sources during compilation—so that part doesn't need to be touched.
内容的提问来源于stack exchange,提问作者ymc

