Python lesson for shell scripts that parse argument parsing without polluting docstring with os.popen ()

Is there a way to write a python doctrine line to test a script that should be run from the command line (terminal) that does not pollute the documentation examples with os.popen calls?

#!/usr/bin/env python # filename: add """ Example: >>> import os >>> os.popen('add -n 1 2').read().strip() '3' """ if __name__ == '__main__': from argparse import ArgumentParser p = ArgumentParser(description=__doc__.strip()) p.add_argument('-n',type = int, nargs = 2, default = 0,help = 'Numbers to add.') p.add_argument('--test',action = 'store_true',help = 'Test script.') a = p.parse_args() if a.test: import doctest doctest.testmod() if an and len(an)==2: print an[0]+an[1] 

Running doctest.testmod () without using popen just causes the test to fail, because the script is executed inside the python shell instead of the bash (or DOS) shell.

LLNL's advanced python course suggests placing scripts in files that are separate from .py modules. But then doctrine lines only check the module without arg analysis. And my os.popen () method pollutes the documentation of the examples. Is there a better way?

+8
source share
3 answers

Just found something similar to your answer: shell-doctest .

+4
source

doctest designed to run python code, so you need to do something. If you decide to test the command line interface directly through doctest , one possibility is to do the regular expression __doc__ before __doc__ before passing it to argparse to take out the os.popen wrapper:

 clean = re.sub(r"^>>> os\.popen\('(.*)'\).*", r"% \1", __doc__) p = ArgumentParser(description=clean, ...) 

(Of course, there are all sorts of nicer ways to do this, depending on what you think is "enjoyable.")

This will clear it for the end user. If you also want it to look cleaner in the source, you can go the other way: Put the command line examples in docstring and do not use doctest.testmodule (). Run docstring via doctest.script_from_examples and follow its post to insert os calls. (Then you have to inject it into something so that you can check it with run_docstring_examples .) doctest doesn't care if the input is valid python, so you can do the following:

 >>> print doctest.script_from_examples(""" Here is a commandline example I want converted: >>> add -n 3 4 7 """) # Here is a commandline example I want converted: add -n 3 4 # Expected: ## 7 

This will still output the python >>> prompt in the help. If this bothers you, you just need to process the string in both directions.

+1
source

You can also load the documentation line and execute the command, for example, in this test .

 import sys module = sys.modules[__name__] docstring = module.__doc__ # search in docstring for certain regex, and check that the following line(s) matches a pattern. 
+1
source

Source: https://habr.com/ru/post/912215/


All Articles