Python教程

仅需5道题轻松掌握Python命令行相关标准库 | Python技能树征题

本文主要是介绍仅需5道题轻松掌握Python命令行相关标准库 | Python技能树征题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

仅需5道题轻松掌握Python命令行相关标准库 | Python技能树征题

    • 0. 前言
    • 1. 第 1 题:命令行日志记录
    • 2. 第 2 题:将日志存储在磁盘上
    • 3. 第 3 题:命令行参数解析
    • 4. 第 4 题:运行系统命令
    • 5. 第 5 题:命令行中进度条显示
    • 试题代码地址

0. 前言

许多用户习惯于使用命令行工具与系统进行交互,因此 Python 中的提供了相应的标准库,用于向通过 shell 和文本与用户进行交互的软件提供常见方法和函数,我们就通过 5Python 编程题来掌握 Python 相关标准库玩转命令行!

1. 第 1 题:命令行日志记录

知识点描述:使用 Python logging 模块记录运行信息。
问题描述:默认情况下 logging 模块只会输出错误信息,如何使 logging 记录程序运行中包括警告等更普通的运行信息,请从以下选项中选出你认为正确的答案:
A.

import logging, sys
logging.basicConfig(level=logging.INFO, stream=sys.stderr, format='%(asctime)s %(name)s %(levelname)s %(message)s')
log = logging.getLogger(__name__)
def my_add(a, b, weight=1):
    log.info('Starting add')
    if a == b == 0:
        log.warning('Warning! 0 for any one')
    res = (a + b) * weight
    log.info('(%s + %s) * %s = %s' % (a, b, weight, res))
    print(res)
if __name__ == '__main__':
    my_add(5, 3)
    my_add(0, 0)

B.

import logging, sys
logging.basicConfig(level=logging.ERROR, stream=sys.stderr, format='%(asctime)s %(name)s %(levelname)s %(message)s')
log = logging.getLogger(__name__)
def my_add(a, b, weight=1):
    log.info('Starting add')
    if a == b == 0:
        log.warning('Warning! 0 for any one')
    res = (a + b) * weight
    log.info('(%s + %s) * %s = %s' % (a, b, weight, res))
    print(res)
if __name__ == '__main__':
    my_add(5, 3)
    my_add(0, 0)

C.

import logging, sys
logging.basicConfig(level=logging.NOTSET, stream=sys.stderr, format='%(asctime)s %(name)s %(levelname)s %(message)s')
log = logging.getLogger(__name__)
def my_add(a, b, weight=1):
    log.info('Starting add')
    if a == b == 0:
        log.warning('Warning! 0 for any one')
    res = (a + b) * weight
    log.info('(%s + %s) * %s = %s' % (a, b, weight, res))
    print(res)
if __name__ == '__main__':
    my_add(5, 3)
    my_add(0, 0)

D.

import logging, sys
logging.basicConfig(level=logging.WARN, stream=sys.stderr, format='%(asctime)s %(name)s %(levelname)s %(message)s')
log = logging.getLogger(__name__)
def my_add(a, b, weight=1):
    log.info('Starting add')
    if a == b == 0:
        log.warning('Warning! 0 for any one')
    res = (a + b) * weight
    log.info('(%s + %s) * %s = %s' % (a, b, weight, res))
    print(res)
if __name__ == '__main__':
    my_add(5, 3)
    my_add(0, 0)

正确答案: A

2. 第 2 题:将日志存储在磁盘上

知识点描述:将日志信息写入磁盘文件中。
问题描述:编写斐波那契计算函数,并用日志文件记录计算出的数字以及运行时间,请从以下选项中选出你认为正确的答案:
A.

import logging, sys
import datetime
def f(n):
    log.info('Computing up to %sth fibonacci number', n)
    a, b = 0, 1
    for n in range(n):
        a, b = b, a+b
        print(b, '', end='')
    print(b)
logging_file = 'log.txt'
logging.basicConfig(level=logging.WARN, filename=logging_file, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
log = logging.getLogger(__name__)
if __name__ == '__main__':
    f(datetime.datetime.now().second)

B.

import logging, sys
import datetime
def f(n):
    log.info('Computing up to %sth fibonacci number', n)
    a, b = 0, 1
    for n in range(n):
        a, b = b, a+b
        print(b, '', end='')
    print(b)
logging_file = 'log.txt'
logging.basicConfig(level=logging.WARN, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
log = logging.getLogger(__name__)
if __name__ == '__main__':
    f(datetime.datetime.now().second)

C.

import logging, sys
import datetime
def f(n):
    log.info('Computing up to %sth fibonacci number', n)
    a, b = 0, 1
    for n in range(n):
        a, b = b, a+b
        print(b, '', end='')
    print(b)
logging_file = 'log.txt'
logging.basicConfig(level=logging.INFO, filename=logging_file, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
log = logging.getLogger(__name__)
if __name__ == '__main__':
    f(datetime.datetime.now().second)

D.

import logging, sys
import datetime
def f(n):
    a, b = 0, 1
    for n in range(n):
        a, b = b, a+b
        print(b, '', end='')
    print(b)
logging_file = 'log.txt'
logging.basicConfig(level=logging.INFO, filename=logging_file, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
log = logging.getLogger(__name__)
if __name__ == '__main__':
    f(datetime.datetime.now().second)

正确答案: C

3. 第 3 题:命令行参数解析

知识点描述:编写命令行工具,根据提供给脚本的选项参数改变程序行为。
问题描述:编写命令行工具,根据提供给脚本的选项参数可以运行多个数据间的加/减/乘/除,请从以下选项中选出你认为正确的选项:
A.

import argparse
import operator
import logging
import functools
parser = argparse.ArgumentParser(description='Applies an operation to one or more numbers')
parser.add_argument("number", help="One or more numbers to perform an operation on.", type=int)
parser.add_argument('-o', '--operation', help="The operation to perform on numbers.", choices=['add', 'sub', 'mul', 'div'], default='add')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
opts = parser.parse_args()
logging.basicConfig(level=logging.INFO if opts.verbose else logging.WARNING)
log = logging.getLogger()
operation = getattr(operator, opts.operation)
log.info('Applying %s to %s', opts.operation, opts.number)
print(functools.reduce(operation, opts.number))

B.

import argparse
import operator
import logging
import functools
parser = argparse.ArgumentParser(description='Applies an operation to one or more numbers')
parser.add_argument("number", help="One or more numbers to perform an operation on.", nargs='+')
parser.add_argument('-o', '--operation', help="The operation to perform on numbers.", choices=['add', 'sub', 'mul', 'div'], default='add')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
opts = parser.parse_args()
logging.basicConfig(level=logging.INFO if opts.verbose else logging.WARNING)
log = logging.getLogger()
operation = getattr(operator, opts.operation)
log.info('Applying %s to %s', opts.operation, opts.number)
print(functools.reduce(operation, opts.number))

C.

import argparse
import operator
import logging
import functools
parser = argparse.ArgumentParser(description='Applies an operation to one or more numbers')
parser.add_argument("number", help="One or more numbers to perform an operation on.", nargs='2', type=int)
parser.add_argument('-o', '--operation', help="The operation to perform on numbers.", choices=['add', 'sub', 'mul', 'div'], default='add')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
opts = parser.parse_args()
logging.basicConfig(level=logging.INFO if opts.verbose else logging.WARNING)
log = logging.getLogger()
operation = getattr(operator, opts.operation)
log.info('Applying %s to %s', opts.operation, opts.number)
print(functools.reduce(operation, opts.number))

D.

import argparse
import operator
import logging
import functools
parser = argparse.ArgumentParser(description='Applies an operation to one or more numbers')
parser.add_argument("number", help="One or more numbers to perform an operation on.", nargs='+', type=int)
parser.add_argument('-o', '--operation', help="The operation to perform on numbers.", choices=['add', 'sub', 'mul', 'div'], default='add')
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
opts = parser.parse_args()
logging.basicConfig(level=logging.INFO if opts.verbose else logging.WARNING)
log = logging.getLogger()
operation = getattr(operator, opts.operation)
log.info('Applying %s to %s', opts.operation, opts.number)
print(functools.reduce(operation, opts.number))

正确答案: D

4. 第 4 题:运行系统命令

知识点描述:在编写系统运维工具时,调用系统命令。

问题描述:编写 Linux 系统运维工具,调用系统命令查看 “/” 目录下文件,请从以下选项中选出你认为正确的选项:
A.

import shlex
import subprocess
def run(command):
    try:
        result = subprocess.getstatusoutput(command, shell=shlex.split(command), stderr=subprocess.STDOUT)
        return 0, result
    except subprocess.CalledProcessError as e:
        return e.returncode, e.output
status, out = run('ls "/"')
print(status, out)

B.

import shlex
import subprocess
def run(command):
    try:
        result = subprocess.check_output(command, shell=shlex.split(command), stderr=subprocess.STDOUT)
        return 0, result
    except subprocess.CalledProcessError as e:
        return e.returncode, e.output
status, out = run('ls "/"')
print(status, out)

C.

import gzip
text = 'text.txt'
with open(text, 'rt') as file:
    read_text = file.read()
    with gzip.open('compress.gz', 'wt', compresslevel = 9) as f:
        f.write(read_text)

D.

import gzip
text = 'text.txt'
with open(text, 'rt') as file:
    read_text = file.read()
    with gzip.open('compress.gz', 'wt', compresslevel = 0) as f:
        f.write(read_text)

正确答案:B

5. 第 5 题:命令行中进度条显示

知识点描述:使用进度条显示当前任务完成进度。
问题描述:在执行耗时任务时,使用进度条显示已经完成了的任务进度,请从以下选项中选出你认为正确的选项:
A.

import shutil, sys
import time
def progressbar(func):
    def _func_with_progress(*args, **kwargs):
        max_width, _ = shutil.get_terminal_size()
        gen = func(*args, **kwargs)
        while True:
            try:
                progress = next(gen)
            except StopIteration as exc:
                sys.stdout.write('\n')
                return exc.value
            else:
                message = '[%s] {}%%'.format(progress)
                bar_width = max_width - len(message) + 3  
                filled = int(round(bar_width / 100.0 * progress))
                spaceleft = bar_width - filled
                bar = '=' * filled + ' ' * spaceleft
                sys.stdout.write((message+'\r') % bar)
                sys.stdout.flush()
@progressbar
def wait(seconds):
    start = time.time()
    step = seconds / 100.
    for i in range(1, 101):
        time.sleep(step)
        yield i
    return time.time() - start
if __name__ == '__main__':
    print("Waiting", wait(4))

B.

import shutil, sys
import time
def progressbar(func):
    def _func_with_progress(*args, **kwargs):
        max_width, _ = shutil.get_terminal_size()
        gen = func(*args, **kwargs)
        while True:
            try:
                progress = next(gen)
            except StopIteration as exc:
                sys.stdout.write('\n')
                return exc.value
            else:
                message = '[%s] {}%%'.format(progress)
                bar_width = max_width - len(message) + 3  
                filled = int(round(bar_width / 100.0 * progress))
                spaceleft = bar_width - filled
                bar = '=' * filled + ' ' * spaceleft
                sys.stdout.write((message+'\r') % bar)
                sys.stdout.flush()
    return _func_with_progress
@progressbar
def wait(seconds):
    start = time.time()
    step = seconds / 100.
    for i in range(1, 101):
        time.sleep(step)
    return time.time() - start
if __name__ == '__main__':
    print("Waiting", wait(4))

C.

import shutil, sys
import time
def progressbar(func):
    def _func_with_progress(*args, **kwargs):
        max_width, _ = shutil.get_terminal_size()
        gen = func(*args, **kwargs)
        while True:
            try:
                progress = next(gen)
            except StopIteration as exc:
                sys.stdout.write('\n')
                return exc.value
            else:
                message = '[%s] {}%%'.format(progress)
                bar_width = max_width - len(message) + 3  
                filled = int(round(bar_width / 100.0 * progress))
                spaceleft = bar_width - filled
                bar = '=' * filled + ' ' * spaceleft
                sys.stdout.write((message+'\r') % bar)
                sys.stdout.flush()
    return _func_with_progress
@progressbar
def wait(seconds):
    start = time.time()
    step = seconds / 100.
    for i in range(1, 101):
        time.sleep(step)
        yield i
    return time.time() - start
if __name__ == '__main__':
    print("Waiting", wait(4))

D.

import shutil, sys
import time
def progressbar(func):
    def _func_with_progress(*args, **kwargs):
        max_width, _ = shutil.get_terminal_size()
        gen = func(*args, **kwargs)
        while True:
            try:
                progress = next(gen)
            except StopIteration as exc:
                sys.stdout.write('\n')
                return exc.value
            else:
                message = '[%s] {}%%'.format(progress)
                bar_width = max_width - len(message) + 3  
                filled = int(round(bar_width / 100.0 * progress))
                spaceleft = bar_width - filled
                bar = '=' * filled + ' ' * spaceleft
                sys.stdout.write((message+'\r') % bar)
                sys.stdout.flush()
    return _func_with_progress()
@progressbar
def wait(seconds):
    start = time.time()
    step = seconds / 100.
    for i in range(1, 101):
        time.sleep(step)
        yield i
    return time.time() - start
if __name__ == '__main__':
    print("Waiting", wait(4))

正确答案:C

试题代码地址

https://codechina.csdn.net/LOVEmy134611/python_problem

这篇关于仅需5道题轻松掌握Python命令行相关标准库 | Python技能树征题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!