[英]python - beginner - integrating optparse in a program
我已經開始認真學習Python作為我的第一門編程語言,並掌握一些算法基礎知識。 由於每個人都建議最好的方法是找到有用的東西,我決定用一個小腳本來管理我的存儲庫。
基本事項: - 啟用/禁用YUM存儲庫 - 更改當前YUM存儲庫的優先級 - 添加/刪除存儲庫
雖然解析文件並替換/添加/刪除數據非常簡單,但我正在努力(主要是可能缺乏知識)與'optparse'的單一事物......我想添加一個選項(-l)列出了當前可用的存儲庫...我已經創建了一個簡單的函數來完成這項工作(不是非常詳細的),但是我無法將它與optparse上的'-l'連接起來。 任何人都可以提供如何做到這一點的例子/建議?
當前腳本是這樣的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import optparse
import ConfigParse
repo_file = "/home/nmarques/my_repos.repo"
parser = optparse.OptionParser()
parser.add_option("-e", dest="repository", help="Enable YUM repository")
parser.add_option("-d", dest="repository", help="Disable YUM repository")
parser.add_option("-l", dest="list", help="Display list of repositories", action="store_true")
(options, args) = parser.parse_args()
def list_my_repos()
# check if repository file exists, read repositories, print and exit
if os.path.exists(repo_file):
config = ConfigParser.RawConfigParser()
config.read(repo_file)
print "Found the following YUM repositories on " + os.path.basename(repo_file) + ":"
for i in config.sections():
print i
sys.exit(0)
# otherwise exit with code 4
else:
print "Main repository configuration (" + repo_file +") file not found!"
sys.exit(4)
list_my_repos()
任何改進的建議(文檔,示例)都是最受歡迎的。 主要目標是,當我執行script.py -l
它可以運行list_my_repos()
。
使用optparse
解析選項對我來說一直是相當不透明的。 使用argparse
有點幫助。
我認為optparse
的見解是optparse
模塊實際上並不幫助您執行命令行中指定的操作。 相反,它可以幫助您從命令行參數中收集信息,您可以在以后執行操作。
在這種情況下,您收集的信息存儲在您的行中的元組(options, args)
中:
(options, args) = parser.parse_args()
要實際處理此信息,您必須自己檢查代碼。 我喜歡在程序結束時將這樣的東西放在一個塊中, 只有從命令行調用它才會運行 。
if __name__ == '__main__':
if options.list:
list_my_repos()
為了使它的工作方式更加清晰,通過使用sys.argv
,有助於意識到你可以在沒有optparse的情況下做同樣的事情。
import sys
if __name__ == '__main__':
if sys.argv[1] == '-l':
list_my_repos()
但是,你可能會看到,這將是一個非常脆弱的實現。 能夠處理更復雜的案例而不用太多自己的編程就是optparse
/ argparse
給你買的東西。
首先, optparse文檔說庫已被棄用,你應該使用argparse 。 所以我們這樣做:
import argparse
parser = argparse.ArgumentParser() #Basic setup
parser.add_argument('-l', action='store_true') #Tell the parser to look for "-l"
#The action='store_true' tells the parser to set the value to True if there's
#no value attached to it
args = parser.parse_args() #This gives us a list of all the arguments
#Passing the args -l will give you a namespace with "l" equal to True
if args.l: #If the -l argument is there
print 'Do stuff!' #Go crazy
祝學習Python好運:)
您沒有在代碼中使用-l標志。 該文檔顯示如何檢查標志是否存在。 http://docs.python.org/library/optparse.html
(options, args) = parser.parse_args()
if options.list:
list_my_repos()
return
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.