2012-03-28 1 views
2

Я пытаюсь начать использовать Sphinx для документирования моих небольших проектов, , но похоже, что я не могу заставить его работать.Sphinx: ImportError при попытке autodoc пакета

Я уже искал, но все, что я пробовал до сих пор, не исправил импортную эрро.

Вот именно то, что я делаю:

[email protected]:~$ mkdir sphinx-test 
[email protected]:~$ cd sphinx-test/ 
[email protected]:~/sphinx-test$ mkdir -p src/package doc 
[email protected]:~/sphinx-test$ touch src/package/__init__.py 
[email protected]:~/sphinx-test$ echo '"""Docstring 1""" 
> class Test(object): 
>  """Docstring 2""" 
>  
>  def method(self): 
>   """Docstring 3""" 
>   pass 
> ' > src/package/testing.py 
[email protected]:~/sphinx-test$ cd doc 
[email protected]:~/sphinx-test/doc$ sphinx-quickstart 
Welcome to the Sphinx 1.0.1 quickstart utility. 

Please enter values for the following settings (just press Enter to 
accept a default value, if one is given in brackets). 

Enter the root path for documentation. 
> Root path for the documentation [.]: 

You have two options for placing the build directory for Sphinx output. 
Either, you use a directory "_build" within the root path, or you separate 
"source" and "build" directories within the root path. 
> Separate source and build directories (y/N) [n]: y 

Inside the root directory, two more directories will be created; "_templates" 
for custom HTML templates and "_static" for custom stylesheets and other static 
files. You can enter another prefix (such as ".") to replace the underscore. 
> Name prefix for templates and static dir [_]: 

The project name will occur in several places in the built documentation. 
> Project name: testing 
> Author name(s): A B 

Sphinx has the notion of a "version" and a "release" for the 
software. Each version can have multiple releases. For example, for 
Python the version is something like 2.5 or 3.0, while the release is 
something like 2.5.1 or 3.0a1. If you don't need this dual structure, 
just set both to the same value. 
> Project version: 0.1 
> Project release [0.1]: 

The file name suffix for source files. Commonly, this is either ".txt" 
or ".rst". Only files with this suffix are considered documents. 
> Source file suffix [.rst]: 

One document is special in that it is considered the top node of the 
"contents tree", that is, it is the root of the hierarchical structure 
of the documents. Normally, this is "index", but if your "index" 
document is a custom template, you can also set this to another filename. 
> Name of your master document (without suffix) [index]: 

Sphinx can also add configuration for epub output: 
> Do you want to use the epub builder (y/N) [n]: 

Please indicate if you want to use one of the following Sphinx extensions: 
> autodoc: automatically insert docstrings from modules (y/N) [n]: y 
> doctest: automatically test code snippets in doctest blocks (y/N) [n]: y 
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]: 
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]: 
> coverage: checks for documentation coverage (y/N) [n]: 
> pngmath: include math, rendered as PNG images (y/N) [n]: 
> jsmath: include math, rendered in the browser by JSMath (y/N) [n]: 
> ifconfig: conditional inclusion of content based on config values (y/N) [n]: 
> viewcode: include links to the source code of documented Python objects (y/N) [n]: 

A Makefile and a Windows command file can be generated for you so that you 
only have to run e.g. `make html' instead of invoking sphinx-build 
directly. 
> Create Makefile? (Y/n) [y]: 
> Create Windows command file? (Y/n) [y]: 

Finished: An initial directory structure has been created. 

You should now populate your master file ./source/index.rst and create other documentation 
source files. Use the Makefile to build the docs, like so: 
    make builder 
where "builder" is one of the supported builders, e.g. html, latex or linkcheck. 

[email protected]:~/sphinx-test/doc$ vim source/conf.py # sys.path.append('../../src') 
[email protected]:~/sphinx-test/doc$ echo ' 
> Title 
> ===== 
> 
> .. automodule:: package.testing 
>  :members: 
> 
> ..autoclass:: package.testing.Test 
>  :members: 
> 
> .. automethod:: package.testing.Test.method 
> ' > source/testing.rst 
[email protected]:~/sphinx-test/doc$ vim source/testing.rst #correct the typo: ..autoclass -> .. autoclass 
[email protected]:~/sphinx-test/doc$ vim source/index.rst #add testing in the toctree 
[email protected]:~/sphinx-test/doc$ make html 
sphinx-build -b html -d build/doctrees source build/html 
Making output directory... 
Running Sphinx v1.0.1 
loading pickled environment... not yet created 
building [html]: targets for 2 source files that are out of date 
updating environment: 2 added, 0 changed, 0 removed 
reading sources... [100%] testing                      
/home/giacomo/sphinx-test/doc/source/testing.rst:5: (WARNING/2) autodoc can't import/find module 'package.testing', it reported error: "No module named package.testing", please check your spelling and sys.path 

/home/giacomo/sphinx-test/doc/source/testing.rst:8: (WARNING/2) autodoc can't import/find class 'package.testing.Test', it reported error: "No module named package.testing", please check your spelling and sys.path 

/home/giacomo/sphinx-test/doc/source/testing.rst:11: (WARNING/2) autodoc can't import/find method 'package.testing.Test.method', it reported error: "No module named package.testing", please check your spelling and sys.path 

looking for now-outdated files... none found 
pickling environment... done 
checking consistency... done 
preparing documents... done 
writing output... [100%] testing                      
writing additional files... genindex search 
copying static files... done 
dumping search index... done 
dumping object inventory... done 
build succeeded, 3 warnings. 

Build finished. The HTML pages are in build/html. 

Я пробовал также это:

[email protected]:~/sphinx-test/doc$ rm build/html/* 
rm: impossibile rimuovere "build/html/_sources": È una directory 
rm: impossibile rimuovere "build/html/_static": È una directory 
[email protected]:~/sphinx-test/doc$ PYTHONPATH="../src" make html 
sphinx-build -b html -d build/doctrees source build/html 
Running Sphinx v1.0.1 
loading pickled environment... done 
building [html]: targets for 2 source files that are out of date 
updating environment: 0 added, 0 changed, 0 removed 
looking for now-outdated files... none found 
preparing documents... done 
writing output... [100%] testing                      
writing additional files... genindex search 
copying static files... done 
dumping search index... done 
dumping object inventory... done 
build succeeded. 

Build finished. The HTML pages are in build/html. 

Выход кажется обнадеживающим, но на самом деле, если я открываю index.html, нажмите на названии страница тестового модуля полностью пуста. У него просто есть заголовок, никакая докшлина или что-то еще.

Кто-нибудь знает, что я делаю неправильно здесь? Я думал, что ставить .. automodule + .. autoclass будет автоматически показывать эти docstrings, но я не могу их видеть.

EDIT:

Fixed, но я не могу понять, почему ... Вот что я сделал на этот раз (я думаю, что это точно так же, как и раньше)

[email protected]:~$ mkdir sphinx-tests 
[email protected]:~$ cd sphinx-tests/ 
[email protected]:~/sphinx-tests$ mkdir -p src/package doc 
[email protected]:~/sphinx-tests$ touch src/package/__init__.py 
[email protected]:~/sphinx-tests$ echo '"""Docstring 1""" 
> class Test(object): 
>  """Docstring 2""" 
>  def method(self): 
>   """Docstring 3""" 
>   pass 
> ' > src/package/testing.py 
[email protected]:~/sphinx-tests$ cd doc 
[email protected]:~/sphinx-tests/doc$ sphinx-quickstart 
Welcome to the Sphinx 1.0.1 quickstart utility. 

Please enter values for the following settings (just press Enter to 
accept a default value, if one is given in brackets). 

Enter the root path for documentation. 
> Root path for the documentation [.]: 

You have two options for placing the build directory for Sphinx output. 
Either, you use a directory "_build" within the root path, or you separate 
"source" and "build" directories within the root path. 
> Separate source and build directories (y/N) [n]: y 

Inside the root directory, two more directories will be created; "_templates" 
for custom HTML templates and "_static" for custom stylesheets and other static 
files. You can enter another prefix (such as ".") to replace the underscore. 
> Name prefix for templates and static dir [_]: 

The project name will occur in several places in the built documentation. 
> Project name: Test 
> Author name(s): A B 

Sphinx has the notion of a "version" and a "release" for the 
software. Each version can have multiple releases. For example, for 
Python the version is something like 2.5 or 3.0, while the release is 
something like 2.5.1 or 3.0a1. If you don't need this dual structure, 
just set both to the same value. 
> Project version: 0.1 
> Project release [0.1]: 

The file name suffix for source files. Commonly, this is either ".txt" 
or ".rst". Only files with this suffix are considered documents. 
> Source file suffix [.rst]: 

One document is special in that it is considered the top node of the 
"contents tree", that is, it is the root of the hierarchical structure 
of the documents. Normally, this is "index", but if your "index" 
document is a custom template, you can also set this to another filename. 
> Name of your master document (without suffix) [index]: 

Sphinx can also add configuration for epub output: 
> Do you want to use the epub builder (y/N) [n]: 

Please indicate if you want to use one of the following Sphinx extensions: 
> autodoc: automatically insert docstrings from modules (y/N) [n]: y 
> doctest: automatically test code snippets in doctest blocks (y/N) [n]: y 
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]: 
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]: 
> coverage: checks for documentation coverage (y/N) [n]: 
> pngmath: include math, rendered as PNG images (y/N) [n]: 
> jsmath: include math, rendered in the browser by JSMath (y/N) [n]: 
> ifconfig: conditional inclusion of content based on config values (y/N) [n]: 
> viewcode: include links to the source code of documented Python objects (y/N) [n]: 

A Makefile and a Windows command file can be generated for you so that you 
only have to run e.g. `make html' instead of invoking sphinx-build 
directly. 
> Create Makefile? (Y/n) [y]: 
> Create Windows command file? (Y/n) [y]: 

Finished: An initial directory structure has been created. 

You should now populate your master file ./source/index.rst and create other documentation 
source files. Use the Makefile to build the docs, like so: 
    make builder 
where "builder" is one of the supported builders, e.g. html, latex or linkcheck. 

[email protected]:~/sphinx-tests/doc$ echo ' 
> Title 
> ===== 
> 
> .. automodule:: package.testing 
>  :members: 
> 
> .. autoclass:: package.testing.Test 
>  :members: 
> 
> .. automethod:: package.testing.Test.method 
> ' > source/testing.rst 
[email protected]:~/sphinx-tests/doc$ vim source/index.rst # add testing to toctree 
[email protected]:~/sphinx-tests/doc$ vim source/conf.py  #sys.path.append('../../src') 
[email protected]:~/sphinx-tests/doc$ make html 
sphinx-build -b html -d build/doctrees source build/html 
Making output directory... 
Running Sphinx v1.0.1 
loading pickled environment... not yet created 
building [html]: targets for 2 source files that are out of date 
updating environment: 2 added, 0 changed, 0 removed 
reading sources... [100%] testing                      
looking for now-outdated files... none found 
pickling environment... done 
checking consistency... done 
preparing documents... done 
writing output... [100%] testing                      
writing additional files... genindex py-modindex search 
copying static files... done 
dumping search index... done 
dumping object inventory... done 
build succeeded. 

Build finished. The HTML pages are in build/html. 
[email protected]:~/sphinx-tests/doc$ 

Btw: извините за многие строки кода.

EDIT 2:

Я обнаружил, что если я очистить каталог сборки/HTML ошибок не проявленные AutoDoc но сгенерированные файлы для модулей являются пустыми. Никакой докштрины не отображается (даже если раньше, когда я сказал, что она была зафиксирована, докстроны были показаны правильно ...).

Если я оставляю пустые папки _sources и _static в папке build/html, чем autodoc, не найдет модули.

Действительно, я не понимаю, что происходит.

EDIT 3:

Хорошо, теперь это совершенно сумасшедший:

[email protected]:~/Progetti/TagEditor/doc$ rm -fr build/html/* 
[email protected]:~/Progetti/TagEditor/doc$ make html 
sphinx-build -b html -d build/doctrees source build/html 
[...]taglib                      
/home/giacomo/Progetti/TagEditor/doc/source/fields.rst:4: (WARNING/2) autodoc can't import/find module 'taglib.fields', it reported error: "No module named taglib.fields", please check your spelling and sys.path 

/home/giacomo/Progetti/TagEditor/doc/source/taglib.rst:4: (WARNING/2) autodoc can't import/find module 'taglib', it reported error: "No module named taglib", please check your spelling and sys.path 
[...] 
build succeeded, 2 warnings. 

Build finished. The HTML pages are in build/html. 
[email protected]:~/Progetti/TagEditor/doc$ rm -fr build/html/* 
[email protected]:~/Progetti/TagEditor/doc$ make html 
sphinx-build -b html -d build/doctrees source build/html 
[...] 
build succeeded. 

Build finished. The HTML pages are in build/html. 

Похоже программа не является детерминированным, но «работает» случайным образом (до сих пор файлы модуля документации пустые) ,

Теперь я начинаю думать, что было бы лучше сменить программное обеспечение.

EDIT 4:

Я переписал один из модулей и теперь автодки работает отлично ... Но я не изменил любой импорт в любом модуле (я подумал, что, может быть, это была ошибка моего модуля), поэтому я действительно озадачен этими изменениями результатов.

Извините за то, что написал такой длинный вопрос без ответа. В любом случае, я все еще с нетерпением жду того, кто знает, что происходит.

+0

Правильные пути? Вы выполняете 'sys.path.append ('../../ src')', что в основном означает '~/src', но модуль находится в' ~/sphinx-test/doc/source'. Может, я что-то неправильно понял? Кроме того, попробуйте использовать 'os.path.abspath()' на пути. –

+0

Да, они есть. Сначала я пробовал «../src», но, похоже, autodoc меняет рабочий каталог на doc/source, поэтому ../ -> doc, а не родитель doc. В любом случае, сейчас я повторил то, что делал раньше, и модуль get был задокументирован правильно. Я понятия не имею, что это зафиксировало. Я не смоделировал/установил/удалил что-нибудь в среднем, просто перезапустил свой ноутбук. – Bakuriu

ответ

3

Sphinx рассолывает окружающую среду и toctree. Иногда я испытывал странное поведение с этим «кешированием».

Вы можете использовать make clean (что будет rm вся сборка) до make html. Итак, все считывается из ваших измененных файлов, и возможные ошибки удаляются.

+0

Большое вам спасибо! Это объясняет, что происходит. В любом случае они должны документировать это ... Я имею в виду, что вызов «помочь» не показывает эту возможность! – Bakuriu

 Смежные вопросы

  • Нет связанных вопросов^_^