WHCSRL 技术网

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

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

正确答案: 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

正确答案: 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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

正确答案: 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

正确答案: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('
')
                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+'
') %%%% 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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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('
')
                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+'
') %%%% 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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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('
')
                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+'
') %%%% 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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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('
')
                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+'
') %%%% 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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

正确答案:C

试题代码地址

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

推荐阅读