杰瑞科技汇

Python 3.6中python.h找不到怎么解决?

Of course. This is a very common point of confusion for developers working with C extensions for Python. Here’s a detailed breakdown of what python.h is, why you need it, and how to get it for Python 3.6.

Python 3.6中python.h找不到怎么解决?-图1
(图片来源网络,侵删)

What is python.h?

python.h is the primary header file for the Python C API. It's the bridge between C/C++ code and the Python interpreter.

Think of it as a "translation dictionary" that allows you to:

  • Embed Python: Write a C/C++ application that can execute Python scripts, access Python objects, and call Python functions.
  • Extend Python: Write new Python modules in C/C++. These modules can be imported and used just like any other Python module, but they execute at C speed.
  • Understand the CPython Internals: It contains definitions for all the core Python types (PyObject, PyList, PyDict, etc.), functions for creating and manipulating them (PyList_New, PyDict_SetItemString), and macros for reference counting (Py_INCREF, Py_DECREF).

In short: If you want to build anything that communicates with the CPython interpreter at a low level, you need python.h.


Why is it Not Found?

The error fatal error: python.h: No such file or directory means the C compiler (gcc or clang) cannot find this file. This almost always happens for one of two reasons:

Python 3.6中python.h找不到怎么解决?-图2
(图片来源网络,侵删)
  1. You don't have Python development headers installed. The standard Python interpreter (the one you download from python.org or install via apt/yum) often comes in two packages:

    • The runtime environment (python3, python3.6, python3.6). This is what you need to run Python scripts.
    • The development headers and libraries (python3-dev, python3.6-dev, python3-devel). This is what you need to build extensions against Python. This package contains python.h, the libpython3.6.a static library, and other necessary files.
  2. The Python installation is not in the compiler's search path. Even if you have the dev files, if they are in a non-standard location (like a custom --prefix installation), you need to tell the compiler where to look.


How to Install python.h for Python 3.6

The method depends on your operating system.

On Debian / Ubuntu / Linux Mint

You need to install the python3.6-dev package. It's best to also install build-essential to get all the necessary C/C++ build tools.

Python 3.6中python.h找不到怎么解决?-图3
(图片来源网络,侵删)
# Update your package list
sudo apt-get update
# Install build tools and Python 3.6 development headers
sudo apt-get install build-essential python3.6-dev

On CentOS / RHEL / Fedora

You need the python3-devel package. You may also need the Development Tools group.

# Install development tools and Python 3.6 development headers
sudo yum groupinstall "Development Tools"
sudo yum install python3-devel

Note: If you are using a specific version like 6, you might need a package like python36-devel or use a Software Collections (SCL) repository.

On macOS

If you installed Python 3.6 using Homebrew, the development headers are automatically included and linked correctly. You don't need to do anything extra.

# Install Python 3.6 via Homebrew
brew install python@3.6
# Homebrew sets up sylinks and paths so the compiler finds python.h
# You can verify with brew info python@3.6

On Windows

This is the trickiest. python.h is included in the Python installation directory. The key is to tell your compiler where to find it.

  1. Install Python 3.6: Make sure you check the box that says "Add Python 3.6 to PATH" during installation. This is the most important step.

  2. Find the Installation Path: The path will look something like this: C:\Users\YourUser\AppData\Local\Programs\Python\Python36-32 or C:\Python36

  3. Set Environment Variables:

    • Open the Environment Variables settings (search for it in the Start Menu).
    • Under "System variables", find the Path variable and click "Edit...".
    • Add two new entries:
      • The path to the include directory: C:\Users\...Python36-32\Include
      • The path to the libs directory: C:\Users\...Python36-32\Libs
  4. Verify: Open a new Developer Command Prompt for VS (this gives you cl.exe, the MSVC compiler) and run:

    cl /I "C:\Users\YourUser\AppData\Local\Programs\Python\Python36-32\Include" /c my_extension.c

    If it compiles without an error about python.h, you're all set. The /I flag explicitly tells the compiler where to look for headers.


Example: Compiling a Simple "Hello World" Extension

Let's put it all together. This is the most basic C extension you can write.

Step 1: Create the C file (hello.c)

#include <Python.h>
// This is the function that will be called from Python
static PyObject* hello_world(PyObject* self, PyObject* args) {
    return PyUnicode_FromString("Hello, C Extension World!");
}
// This is the module definition
static PyMethodDef HelloMethods[] = {
    {"hello", hello_world, METH_NOARGS, "Prints a friendly greeting."},
    {NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef hello_module = {
    PyModuleDef_HEAD_INIT,
    "hello",   /* name of module */
    NULL,      /* module documentation, may be NULL */
    -1,        /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
    HelloMethods
};
// The module initialization function
PyMODINIT_FUNC PyInit_hello(void) {
    return PyModule_Create(&hello_module);
}

Step 2: Create the setup.py script

This script tells Python's build system how to compile your C code.

from setuptools import setup, Extension
# Define the extension module
module = Extension('hello',
                   sources=['hello.c'])
# Build the module
setup(name='HelloWorldPackage',
      version='1.0',
      description='A simple Hello World Extension',
      ext_modules=[module])

Step 3: Compile and Install

Open your terminal or command prompt in the same directory as hello.c and setup.py, and run:

# This command builds and installs the extension into your Python 3.6 environment
python3.6 setup.py build_ext --inplace
  • python3.6 setup.py build_ext: Tells setuptools to build an extension module.
  • --inplace: Installs the compiled module (e.g., hello.so or hello.pyd) directly in the current directory instead of the main site-packages directory.

Step 4: Use the Extension

Now, create a Python file (test.py) to use your new C module.

import hello
# Call the function we defined in C
greeting = hello.hello()
print(greeting)
print(type(greeting))

Run it:

python3.6 test.py

Expected Output:

Hello, C Extension World!
<class 'str'>
分享:
扫描分享到社交APP
上一篇
下一篇