首页 > 解决方案 > 如何让 Sphinx 将 pandas 识别为模块

问题描述

我正在Python 3.9.2使用sphinx-build 3.5.2. 我创建了一个具有以下目录和文件结构的项目

core_utilities
  |_core_utilities
  |   |_ __init__.py
  |   |_read_files.py
  |_docs
      |_ sphinx
           |_Makefile
           |_conf.pg
           |_source
           |    |_conf.py
           |    |_index.rst
           |    |_read_files.rst
           |_build

read_files.py文件包含以下代码。注意:我简化了这个例子,所以它不会有分散注意力的信息。在这段代码中,它们是一个包含一个成员函数的类,用于读取文本文件、查找关键字并将关键字右侧的变量作为numpy.float32变量读取。编写用于读取具有特定数据类型的 csv 文件并将其保存到 pandas 数据帧的独立函数。

# Import packages here
import os
import sys
import numpy as np
import pandas as pd
from typing import List

class ReadTextFileKeywords:

    def __init__(self, file_name: str):
        self.file_name = file_name
        if not os.path.isfile(file_name):
            sys.exit('{}{}{}'.format('FATAL ERROR: ', file_name, ' does not exist'))
# ----------------------------------------------------------------------------

    def read_double(self, key_words: str) -> np.float64:
        values = self.read_sentence(key_words)
        values = values.split()
        return np.float64(values[0])

# ================================================================================
# ================================================================================


def read_csv_columns_by_headers(file_name: str, headers: List[str],
                                data_type: List[type],
   
    if not os.path.isfile(file_name):
        sys.exit('{}{}{}'.format('FATAL ERROR: ', file_name, ' does not exist'))
    dat = dict(zip(headers, data_type))
    df = pd.read_csv(file_name, usecols=headers, dtype=dat, skiprows=skip)
    return df

conf.py 文件中包含如下信息。

# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../../../core_utilities'))

# -- Project information -----------------------------------------------------

project = 'Core Utilities'
copyright = 'my copyright'
author = 'my name'

# The full version, including alpha/beta/rc tags
release = '0.1.0'


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.autodoc',
              'sphinx.ext.autosummary', 'sphinx.ext.githubpages']
autodoc_member_order = 'groupwise'
autodoc_default_flags = ['members', 'show-inheritance']
autosummary_generate = True
autodock_mock_imports = ['numpy']

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'nature'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

index.rst文件包含以下信息。

. Core Utilities documentation master file, created by
   sphinx-quickstart 
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Core Utilities's documentation!
==========================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   read_files


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

并且该read_files.rst文件具有以下信息

**********
read_files
**********

The ``read_files`` module contains methods and classes that allow a user to read different
types of files in different ways.  Within the module a user will find functionality that 
allows them to read text files and csv files by columns and keywords.  This module
also contains functions to read sqlite databases, xml files, json files, yaml files, 
and html files

.. autoclass:: test.ReadTextFileKeywords
   :members:

.. autofunction:: test.read_csv_columns_by_headers

此外,当我尝试使用命令行编译它时,我正在使用一个处于活动状态的虚拟环境。我运行以下命令来用 sphinx 编译 html 文件。

sphinx-build -b html source build

当我运行上述命令时,它失败并出现以下错误。

WARNING: autodoc: failed to import class 'ReadTextFileKeywords' from module 'read_files'; the following exception was raised; No module named pandas.

如果我删除该行from pandas import pd,然后删除该函数read_csv_columns_by_headers以及对read_files.rst文件中函数的调用,则一切编译正常。似乎由于某种原因 sphinx 能够找到numpy,但由于某种原因它似乎无法识别pandas,尽管两者都存在于虚拟环境中并加载了pip3 install语句。有谁知道为什么 sphinx 能够找到其他模块,但不能pandas

标签: python-3.xpandaspython-sphinx

解决方案


推荐阅读