i have these two simple files: this is 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)
and this is 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)
now if i run tone.py with the help switch i get what i expect:
$ 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
but the second one gives unexpected results:
$ 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
this is the help for the first module. what happened? and how do i fix it?
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()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다