Python 中的命令行界面编程?

pythonserver side programmingprogramming更新于 2024/1/24 10:22:00

在本节中,我们将使用 Python 开发命令行界面。但在深入研究程序之前,让我们先了解一下命令行。

自从计算机程序出现以来,命令行就一直在使用,并且基于命令构建。命令行程序是从 shell 或命令行运行的程序

命令行界面提供的用户界面通过在终端、shell 或控制台上键入命令而不是使用鼠标来导航。

命令行界面 (CLI) 以可执行文件开始。我们可以根据脚本的开发方式将参数传递给脚本,例如:

  • 参数:我们需要提供传递给脚本的这个参数。如果我们不提供它,CLI 将通过一个错误。例如,numpy 是此命令中的参数:pip install numpy。

  • 选项:一个可选参数,带有名称和值对,例如:pip install django –cache-dir ./my-cache-dir,其中 –cache_dir 是一个选项参数,值 ./my-cache-dir 应用于缓存目录。

  • 标志:另一个可选参数,它告诉脚本启用或禁用某个行为,例如 –help 参数。

Python 提供了多个 python 包来编写命令行界面,例如‘click’。Click 允许我们用很少的代码行构建命令行界面。

下面是一个不使用 click 包的命令行界面程序。编写 CLI 程序可能不如我们使用‘click’包得到的程序那么优雅,因为‘click’允许您遵循“不要重复自己” (DRY) 原则。

不使用 click 包的命令行界面

import sys
import random

def do_work():
   """ Function to handle command line usage"""
   args = sys.argv
   args = args[1:] # First element of args is the file name

   if len(args) == 0:
      print('You have not passed any commands in!')
   else:
      for a in args:
         if a == '--help':
            print('Basic command line program')
            print('Options:')
            print(' --help -> show this basic help menu.')
            print(' --monty -> show a Monty Python quote.')
            print(' --veg -> show a random vegetable')
         elif a == '--monty':
            print('He’s not the Messiah—he’s a very naughty boy')
         elif a == '--veg':
            print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))
         else:
            print('Unrecognised argument.')

if __name__ == '__main__':
do_work()

输出

c:\Python\Python361>python cli_interp1.py --monty
He’s not the Messiah—he’s a very naughty boy

c:\Python\Python361>python cli_interp1.py --help
Basic command line program
Options:
--help -> show this basic help menu.
--monty -> show a Monty Python quote.
--veg -> show a random vegetable

c:\Python\Python361>python cli_interp1.py --veg
Tomato

c:\Python\Python361>python cli_interp1.py --error
Unrecognised argument.

正如您在上面的程序中看到的,它没有提供太多更改参数名称的灵活性。

下面是使用 python click 包实现 CLI 的相同程序。

import click
import random

@click.command()
@click.option('--monty', default=False, help='Show a Monty Python quote.')
@click.option('--veg', default=False, help='Show a random vegetable.')
def do_work(monty, veg):
""" Basic Click example will follow your commands"""
if monty:
   print('He’s not the Messiah—he’s a very naughty boy')
   if veg:
      print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))
if __name__ == '__main__':
do_work()

输出

c:\Python\Python361>python cli_interp2.py --help
Usage: cli_interp2.py [OPTIONS]

Basic Click example will follow your commands

Options:
--monty TEXT Show a Monty Python quote.
--veg TEXT Show a random vegetable.
--help Show this message and exit.

上面的程序表明,使用‘click’包编写CLI要容易得多,节省了大量程序员的努力。


相关文章