我正在尝试用 python 编写一段代码,以使用 getopt 模块获取命令行选项和参数。 这是我的代码:
import getopt
import sys
def usage ():
print('Usage')
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'xy:')
except getopt.GetoptError as err:
print(err)
usage()
sys.exit()
for o,a in opts:
if o in ("-x", "--xxx"):
print(a)
elif o in ("-y", "--yyy"):
print(a)
else:
usage()
sys.exit()
if __name__ == "__main__":
main()
问题是我无法读取选项x
的参数,但我可以读取y
的参数。我应该怎么做才能解决这个问题?
最佳答案
试试 getopt.getopt(sys.argv[1:], 'x:y:')
http://docs.python.org/library/getopt.html
Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).
关于python - 使用 getopt 的命令行选项和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562616/