Intermediate Python 3. Argparse for CLI 영어 파이썬 코딩영어 смотреть онлайн
LC training(1:57) - So let's convert this to command line interface So the first thing that we're going to do is we're gonna import argparse and we're gonna import sys so then we're gonna do define main and then main is where we're going to actually build the arguments themselves As you might guess from the name argparse it's an argument parser surprise! So what we're going to do is we're going to define the parser and the parser is equal to argparse dot argument parser One quick note on um PEP 8 when i see the following argparse ArgumentParser i am i can assume ArgumentParser is a class and parser equals is an object of that ArgmentParser class How do i know? Because of the studley case Again that's just that's one reason why you want to sometimes adhere to PEP 8 because it's clear to me immediately when i know like that's the name of that okay it's a parser object it's not some sort of function that's returning some sort of value that we're calling parser Moving along parser dot add argument again because we know parser is an object we know add argument's a method that doesn't make much sense to you right Now it will soon because we're going to be talking about Object Oriented Programming soon moving on The first argument we'll add is just dash dash x that's going to take the place of this x parameter So that's the name of it The type we're gonna say is a float then we're gonna say default equals 1.0 and then we're going to come down and we're going to add some help and the help is just like a some sort of string that's going to explain what this is so we're just gonna say what is the first number ... So those are the arguments Now we're going to say the args is equal to parser dot parse the args and then we're just going to sys dot standard out dot write the string version of calc args okay So this is all necessary to do with argparse and then the system out The reason why we're doing this is So the output will actually come to the to the console itself In many cases you could just use print But there's going to be times when actually you need to do a system out Because otherwise you're just not going to see it
Summary & Code results -
coding할 때엔 약간씩 미세조정이 필요한 부분이 나옵니다. 이런건 주 editor IDE 와는 별도로 가볍게 기능시험해보는 용도로 CLI command line interface 가 자주 쓰입니다. 실습에선 CLI 환경에서 arguments를 parse 해 operation을 수행하게 해주는 argparse.ArgumentParser() 란 메소드를 활용해 사칙연산 응용을 만들어냈습니다. help 기능까지 들어간 완벽한 작품이 몇 안되는 코딩으로 가능하다는 것을 보여줍니다.
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=float, default=1.0,
help='What is the first number?')
parser.add_argument('--y', type=float, default=1.0,
help='What is the second number?')
parser.add_argument('--operation', type=str, default='add',
help='What operation? (add, sub, mul, or div)')
args = parser.parse_args()
sys.stdout.write(str(calc(args))) # system out to the console
def calc(args):
if args.operation == 'add':
return args.x + args.y
elif args.operation == 'sub':
return args.x - args.y
elif args.operation == 'mul':
return args.x * args.y
elif args.operation == 'div':
return args.x / args.y
if __name__ == '__main__':
main()
원본 비디오: https://www.youtube.com/watch?v=0twL6MXCLdQ&list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&index=4
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Intermediate Python 3. Argparse for CLI 영어 파이썬 코딩영어» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.