python utility(command line tool)讀取參數技巧ConfigParser, argparse

python很適合拿來寫些小工具程式,也常常需要藉由帶入不同的參數來讓程式更有彈性,如果功能更多或是需要的參數比較複雜一些,藉由讀取設定檔,會是更好的方式。

從GitHub上面一個python專案學到了這樣的方式,可以快速達到這些功能,不用再慢慢寫Parser,下面介紹:

  • 如何用ConfigParser來讀取設定檔的參數
  • 如何用argparse來簡單parse command line參數

1. 讀取設定檔 (ConfigParser)

透過ConfigParser將設定檔讀入,並且用eval將設定值直接assign到python變數。

#
# Read Config from config.ini file
#

config = ConfigParser.ConfigParser()
config.read(os.path.join(os.path.dirname(sys.argv[0]), "uploadr.ini"))
FILES_DIR = eval(config.get('Config', 'FILES_DIR'))
FLICKR = eval(config.get('Config', 'FLICKR'))
SLEEP_TIME = eval(config.get('Config', 'SLEEP_TIME'))
DRIP_TIME = eval(config.get('Config', 'DRIP_TIME'))
DB_PATH = eval(config.get('Config', 'DB_PATH'))
LOCK_PATH = eval(config.get('Config', 'LOCK_PATH'))
TOKEN_PATH = eval(config.get('Config', 'TOKEN_PATH'))
EXCLUDED_FOLDERS = eval(config.get('Config', 'EXCLUDED_FOLDERS'))
IGNORED_REGEX = [re.compile(regex) for regex in eval(config.get('Config', 'IGNORED_REGEX'))]
ALLOWED_EXT = eval(config.get('Config', 'ALLOWED_EXT'))
RAW_EXT = eval(config.get('Config', 'RAW_EXT'))
FILE_MAX_SIZE = eval(config.get('Config', 'FILE_MAX_SIZE'))
MANAGE_CHANGES = eval(config.get('Config', 'MANAGE_CHANGES'))
RAW_TOOL_PATH = eval(config.get('Config', 'RAW_TOOL_PATH'))
CONVERT_RAW_FILES = eval(config.get('Config', 'CONVERT_RAW_FILES'))
FULL_SET_NAME = eval(config.get('Config', 'FULL_SET_NAME'))
SOCKET_TIMEOUT = eval(config.get('Config', 'SOCKET_TIMEOUT'))
MAX_UPLOAD_ATTEMPTS = eval(config.get('Config', 'MAX_UPLOAD_ATTEMPTS'))

ini檔長像下面這樣,有個分類標籤[Config],然後直接指定FILES_DIR="YourDir",或者可以直接指定array,FLICKR = {...},就可以直接在python程式中用eval將設定值或array在assign到python變數中,提供了很大的彈性

[Config]
################################################################################
# Location to scan for new files
################################################################################
FILES_DIR = "YourDir"

################################################################################
# Flickr settings
################################################################################
# Set your own API key and secret message
# Go to http://www.flickr.com/services/apps/create/apply and apply for an API key
#
FLICKR = {
"title" : "",
"description" : "",
"tags" : "auto-upload",
"is_public" : "0",
"is_friend" : "0",
"is_family" : "0",
"api_key" : "YourKey",
"secret" : "YourSecret"
}

2. 設定command參數表 (argparse)

import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Upload files to Flickr.')
parser.add_argument('-d', '--daemon', action='store_true',
help='Run forever as a daemon')
parser.add_argument('-i', '--title', action='store',
help='Title for uploaded files')
parser.add_argument('-e', '--description', action='store',
help='Description for uploaded files')
parser.add_argument('-t', '--tags', action='store',
help='Space-separated tags for uploaded files')
parser.add_argument('-r', '--drip-feed', action='store_true',
help='Wait a bit between uploading individual files')
parser.add_argument('-p', '--processes',
help='Number of photos to upload simultaneously')
parser.add_argument('-n', '--dry-run', action='store_true',
help='Dry run')
args = parser.parse_args()

透過add_argument,自動存下參數,action='store'預設存下string,action='store_true' 為boolean預設為True,之後可以透過args.daemon, args.title…存取執行時帶入的參數

參考自GitHub trickortweak/flickr-uploader

發佈留言