简体   繁体   中英

Why doesn't pydoc work when I use argparse?

Still very new to python, so forgive me if this seems obvious, but I found that argparse prevents me running pydoc on my script.

"""
  Script to blah blah blah
"""

import argparse

parser = argparse.ArgumentParser(description='Script to do something useful')

# If I uncomment this line, pydoc fails !
#args = parser.parse_args()

If I uncomment that last line, and run pydoc scriptname , then pydoc appears to try running the script somehow, rather than just showing a formatted docstring ??

Where am I going wrong ?

pydoc imports the file which means that argparse will then do it's thing. The typical way around this is to set up a conditional that will only run iff the module is imported as the main module:

"""
  Script to blah blah blah
"""

import argparse

parser = argparse.ArgumentParser(description='Script to do something useful')

if __name__ == '__main__':
    args = parser.parse_args()

This is a really well used and understood idiom in the python community, so there isn't any magic going on here that will give your future readers a hard time. Basically, every module has a __name__ attribute (which is the name of the module). The "master" module (the one where python starts it's execution) gets the special name __main__ instead of the typical file basename without the extension.

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