所以,我遇到了getopt
module來解析命令行參數,但我無法理解文檔。 無論出於何種原因,我想不通這是爲什麼不看我--domain example.com
說法..解析不讀取所有參數的命令行參數?
$ ./httpdsetup.py -a -u zack --domain example.com
[('-a', ''), ('-u', '')]
我打印出來什麼獲取倒入opts
,看看它看到的。下面的代碼與文檔站點上的完全相同。
def main(argv):
import getopt
try:
opts, args = getopt.getopt(argv, "h:al:ud:v", ["user=", "apache", "lighttpd", "dir=", "domain=", "vhost="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
username = ''
directory = ''
domain = ''
httpd = 'apache'
print(opts)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ('-u', '--username'):
username = arg
elif opt in ('-d', '--dir'):
directory = arg
elif opt in ('-v', '--domain', '--vhost'):
domain = arg
elif opt in ('-a', '--apache'):
httpd = 'apache'
elif opt in ('-l', '--lighttpd'):
httpd = 'lighttpd'
else:
print_usage()
sys.exit()
if httpd == 'apache':
create_apache_vhost(domain, directory, username)
elif httpd == 'lighttpd':
create_lighty_vhost(domain, directory, username)
if __name__ == '__main__':
main(sys.argv[1:])
不要使用'getopt',使用['argparse'(http://docs.python.org/dev/library/argparse。 HTML)。它更加靈活,並且具有更清晰的IMO接口。 – nneonneo
偶然,你知道Debian軟件包嗎? – Zack
儘管在Debian Squeeze上安裝了「python-argparse」軟件包,但我在導入模塊'argparse'上收到了ImportError。 – Zack