Last active
November 8, 2018 08:29
-
-
Save princewang1994/f49905787fa24b3087cd4a742afc1c2e to your computer and use it in GitHub Desktop.
Python中argparser的使用方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import argparse | |
def main(): | |
parser = argparse.ArgumentParser() | |
# Positional arguments, must be parse | |
parser.add_argument('words', type=str, help='Contents you want to say') | |
# Add argment for enumerable arguments like follow using `choice` keyword | |
parser.add_argument('to', type=str, choices=['Students', 'Teacher'], help='Who do you wanna speak to ?') | |
# Options, usually have default values, if there is no defaults, `None` will set | |
parser.add_argument('--log', '-l', type=str, help='path to log file') | |
parser.add_argument('--repeat', '-r', type=int, default=1, help='how many times to say hello~, default `1`') | |
args = parser.parse_args() | |
repeat = args.repeat | |
to = args.to | |
words = args.words | |
log = args.log | |
# Create a new Note | |
if log: # log is default to be None | |
note = open(log, 'w') | |
for _ in range(repeat): | |
speak = '{0}, I wanna tell you that "{1}"!'.format(to, words) | |
print speak | |
if log: | |
note.write(speak + '\n') | |
if log: | |
print 'I have written down it to {0}'.format(log) | |
note.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment