2015-04-02 46 views
0

我真的很努力地找到一个资源,它实际上解释了如何使用python实现getopt的语法。我看到的每个例子都至少有十行代码,并且都没有解释。我试图用getopt的非常简单的从我的命令行允许键入下列选项getopt for python语法

python test.py -i file.fa 

python test.py -inputfile = file.fa 

我是初学者,所以我真的很努力明白什么语法是必要的,什么是不....这是多远,我已经变得和它不工作:

def main(): 
    try: 
    opts,args = getopt.getopt(sys.argv[1:],":i"["inputfile=",]) 
    for opt,arg in opts: 
     if opt == '-i': 
      inputfile = arg 
+0

您是否尝试了第二个选项,而没有围绕等号的空格? – 2015-04-02 01:38:33

+0

我很确定'“:我”[“inputfile =”,]'应该是'“:i”,[“inputfile =”])' – zwol 2015-04-02 01:41:51

+0

您几乎肯定希望您的长参数以_double_连字符开头: '--inputfile'。这可以防止含多个参数的单个连字符的含糊不清 - 像'program -xml'这样的命令有一个长参数还是三个短参数? – 2015-04-02 02:42:33

回答

2

如果使用Python 2.7或HIG她,你可能会更容易使用argparse,或者如果小于2.7,可以使用optparse

然后有aaargh。每个都有一个相当广泛的例子列表。您可能需要使用pip install或sudo pip install实际安装最后一个。