庆幸的是,Python有很多处理有关命令行参数的模块。我个人比较喜欢OptionParser。OptionParser是标准库提供的optparse模块的一部分。OptionParser允许你对命令行参数做一系列非常有用的操作。
- 如果没有提供具体的参数,可以指定默认的参数
- 它支持参数标志(显示或不显示)和参数值(-n 10000)。
- 它支持传递参数的不同格式——例如,有差别的-n=100000和-n
100000。
我们来用OptionParser来改进sending-mail脚本。原来的脚本有很多的变量硬编码的地方,比如SMTP细节和用户的登录凭据。在下面提供的代码,在这些变量是用来传递命令行参数:
view
source
print?
05 |
from
optparse import
OptionParser |
07 |
def
initialize_smtp_server(smtpserver, smtpport, email, pwd): |
09 |
This function initializes and greets the SMTP server. |
10 |
It logs in using the provided credentials and returns the |
11 |
SMTP server object as a result. |
13 |
smtpserver =
smtplib.SMTP(smtpserver, smtpport) |
17 |
smtpserver.login(email, pwd) |
21 |
def
send_thank_you_mail(email, smtpserver): |
23 |
from_email =
GMAIL_EMAIL |
24 |
subj =
"Thanks for being an active commenter" |
25 |
# The header consists of the To and From and Subject lines |
26 |
# separated using a newline character. |
27 |
header =
"To:%s\nFrom:%s\nSubject:%s \n" %
(to_email, |
29 |
# Hard-coded templates are not best practice. |
33 |
Thank you very much for your repeated comments on our service. |
34 |
The interaction is much appreciated. |
37 |
content =
header + "\n" + msg_body |
38 |
smtpserver.sendmail(from_email, to_email, content) |
41 |
if
__name__ = =
"__main__" : |
42 |
usage =
"usage: %prog [options]" |
43 |
parser =
OptionParser(usage = usage) |
44 |
parser.add_option( "--email" , dest = "email" , |
45 |
help = "email to login to smtp server" ) |
46 |
parser.add_option( "--pwd" , dest = "pwd" , |
47 |
help = "password to login to smtp server" ) |
48 |
parser.add_option( "--smtp-server" , dest = "smtpserver" , |
49 |
help = "smtp server url" , default = "smtp.gmail.com" ) |
50 |
parser.add_option( "--smtp-port" , dest = "smtpserverport" , |
51 |
help = "smtp server port" , default = 587 ) |
52 |
options, args =
parser.parse_args() |
54 |
if
not (options.email or
options.pwd): |
55 |
parser.error( "Must provide both an email and a password" ) |
57 |
smtpserver =
initialize_smtp_server(options.stmpserver, |
58 |
options.smtpserverport, options.email, options.pwd) |
60 |
# for every line of input. |
61 |
for
email in sys.stdin.readlines(): |
62 |
send_thank_you_mail(email, smtpserver) |
这个脚本显示OptionParser 的作用。它提供了一个简单、易于使用的接口给命令行参数,
允许你为每个命令行选项定义某些属性。它还允许你指定默认值。如果没有给出某些参数,它可以给你报出特定错误。
|
1人顶
顶 翻译的不错哦!
|