Ale*_*dro 5 python getopt command-line-arguments
我在Python中使用函数有问题.这是我主要功能的一部分:
def main(argv):
try:
opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
if not opts:
print 'No options supplied'
usage()
except getopt.GetoptError,e:
print e
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(2)
if __name__ =='__main__':
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
我也定义了一个使用函数
def usage():
print "\nThis is the usage function\n"
print 'Usage: '+sys.argv[0]+' -i <file1> [option]'
Run Code Online (Sandbox Code Playgroud)
但当我运行我的代码./code.py或./code.py -h(它是可执行的)时,我得到了除Python帮助之外的任何东西.
以下对我有用.用"python code.py"运行它.
import getopt, sys
def usage():
print "\nThis is the usage function\n"
print 'Usage: '+sys.argv[0]+' -i <file1> [option]'
def main(argv):
try:
opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
if not opts:
print 'No options supplied'
usage()
except getopt.GetoptError,e:
print e
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(2)
if __name__ =='__main__':
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)