Why isn't getopt working if sys.argv is passed fully?

那年仲夏 提交于 2019-12-12 10:53:45

问题


If I'm using this with getopt:

import getopt
import sys

opts,args = getopt.getopt(sys.argv,"a:bc")
print opts
print args

opts will be empty. No tuples will be created. If however, I'll use sys.argv[1:], everything works as expected. I don't understand why that is. Anyone care to explain?


回答1:


The first element of sys.argv (sys.argv[0]) is the name of the script currently being executed. Because this script name is (likely) not a valid argument (and probably doesn't begin with a - or -- anyway), getopt does not recognize it as an argument. Due to the nature of how getopt works, when it sees something that is not a command-line flag (something that does not begin with - or --), it stops processing command-line options (and puts the rest of the arguments into args), because it assumes the rest of the arguments are items that will be handled by the program (such as filenames or other "required" arguments).




回答2:


It's by design. Recall that sys.argv[0] is the running program name, and getopt doesn't want it.

From the docs:

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).

http://docs.python.org/library/getopt.html



来源:https://stackoverflow.com/questions/1540365/why-isnt-getopt-working-if-sys-argv-is-passed-fully

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!