使用 getopt 的命令行选项和参数
我正在尝试在 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
的参数。我应该怎么做才能解决这个问题?
I'm trying to write a piece of code in python to get command-line options and arguments using getopt module.
Here is my code:
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()
The problem is that I can't read the argument of option x
, but I can read the argument of y
. What should I do to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
getopt.getopt(sys.argv[1:], 'x:y:')
http ://docs.python.org/library/getopt.html
Try
getopt.getopt(sys.argv[1:], 'x:y:')
http://docs.python.org/library/getopt.html
如果你想阅读参数,那么选项旁边应该有“:”,有一些选项不需要参数,例如“help”和“verbose”,它们后面不需要“:”。
If you want to read argument then the option should've ':' next to it, there are few options which doesn't need argument like 'help' and 'verbose' which don't need ':' to be followed.