简体   繁体   中英

python-sphinx documenting scripts with no py extension

Apologies - this is a complete n00b question:

I have a couple of python scripts with no .py extension.

How do I convince Sphinx that it should document that script? Example error:

/home/XXX/YYYYY/development/dst/build/index.rst:25: (WARNING/2) autodoc can't import/find module 'site_scons.random', it reported error: "No module named random", please check your spelling and sys.path

In order for your script to be a module, it needs to include the .py suffix. From the Python docs :

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

Without giving it the suffix, Sphinx won't be able to import it to generate documentation using automodule .

If you don't want your script to end with a .py file extension you can also try the following.

You can write your original script into a .py file and create another executable (bash script) file that just executes your .py file. That way, you can document the script (the .py ) file using sphinx and still execute it through the other executable file.

As mentioned by @dirn, a module requires a .py extension to be considered as such.

An alternate solution that I think is cleaner, though it requires more work:

  • Create a directory named links on your Sphinx root folder (that is, it will be a sibling to source and build )
  • On that directory, create relative links to your scripts, adding .py to their names
  • Add this new directory to the Python PATH on conf.py , under Path setup : sys.path.insert(0, os.path.abspath('../links'))
  • Now, you can use something like .. automodule:: my_command to have your script read as a module and documented.

A sample project would look like this:

proj_root/
proj_root/doc              # Sphinx root
proj_root/doc/build
proj_root/doc/links        # Remember to version this
proj_root/doc/links/my_command.py -> ../../bin/my_command
proj_root/doc/source
proj_root/doc/source/conf.py
proj_root/bin
proj_root/bin/my_command   # Actual code

The advantage I see for this method is that you do not polute your bin directory with .py files that are just duplicates of the actual scripts.

One could probably also try to hack this through the imp module to get it, but I think that would be uglier. I haven't tried that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM