2

我有这两个简单的文件:这是tone.py:

import argparse
import os
import sys
root , pyfilename = os.path.split(os.path.abspath(__file__))

try:
    parser = argparse.ArgumentParser()
    parser.add_argument('--argone', help='argument one',default= "one" )
    parser.add_argument('--argtwo', help='argument two',default= "two" )
    parser.add_argument('--argthree', help='argument three',default= "three" )
    parser.add_argument('--argfour', help='argument three',default=False )
    args = parser.parse_args()
except Exception as e:
    print "crapped"

class One():
    pass

if __name__ == "__main__" :
    while True:
        print (args.argone)
        print (args.argtwo)
        print (args.argthree)

这是 ttwo.py:

import argparse
import os
import sys
root , pyfilename = os.path.split(os.path.abspath(__file__))

try:
    from tone  import One
except Exception as e:
    print "cant import module coz: %s ; so i'm exiting"%e
    sys.exit()


try:
    import defaults
    parser = argparse.ArgumentParser()
    parser.add_argument('--arga', help='arga',default= "a" )
    parser.add_argument('--argb', help='argb',default= "b" )
    parser.add_argument('--argc', help='argc',default= "c" )
    parser.add_argument('--argd', help='targd',default=False )
    args = parser.parse_args()
except Exception as e:
    print "crapped"


if __name__ == "__main__" :
    print (args.arga)
    print (args.argb)
    print (args.argc)

现在,如果我使用帮助开关运行tone.py,我会得到我所期望的:

$ python  tone.py -h 
usage: tone.py [-h] [--argone ARGONE] [--argtwo ARGTWO] [--argthree ARGTHREE]
               [--argfour ARGFOUR]

optional arguments:
  -h, --help           show this help message and exit
  --argone ARGONE      argument one
  --argtwo ARGTWO      argument two
  --argthree ARGTHREE  argument three
  --argfour ARGFOUR    argument three

但第二个给出了意想不到的结果:

$ python  ttwo.py -h 
usage: ttwo.py [-h] [--argone ARGONE] [--argtwo ARGTWO] [--argthree ARGTHREE]
               [--argfour ARGFOUR]

optional arguments:
  -h, --help           show this help message and exit
  --argone ARGONE      argument one
  --argtwo ARGTWO      argument two
  --argthree ARGTHREE  argument three
  --argfour ARGFOUR    argument three

这是第一个模块的帮助。发生了什么?我该如何解决?

4

1 回答 1

3

Your tone module defines an argument parser at the module level and prints the help message as it parses your command line arguments

If you only want the parsing to take place if tone is being run as a script, move the parser.parse_args() call to your __main__ test block:

if __name__ == '__main__':
    # run as a script, not imported as a module
    args = parser.parse_args()
于 2013-07-18T12:27:59.817 回答