【问题标题】:Python3: how to use module 'Import click' & Parsing command linePython3:如何使用模块“导入点击”和解析命令行
【发布时间】:2021-05-30 23:06:10
【问题描述】:

我是业余无线电爱好者 [G6SGA] 不是程序员,但我确实尝试过。 :) 使用python3。我正在尝试执行以下操作,但真的无法理解 - argparse 并最终尝试使用“导入点击”。仍然无法理解,所以我在这里。任何所有(礼貌):) 欢迎提出建议。 我希望---

命令行> python3 scratch.py​​ [未提供选项]

output> "你的默认值被使用并且是:9600 and '/dev/ttyAMA0' "

命令行> python3 scratch.py​​ 115200 '/dev/ttyABC123'

output> "你的输入值被使用并且是:115200 and '/dev/ttyAMA0'"

所以命令行将采用 [or NOT] 参数/s。将参数存储到代码中的变量中以供将来使用。 这是我尝试过的一些方法:是的,我接受这是一团糟

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
#   ========================
#   Include standard modules
#   import click
#   baud default = 9600
#   port default = "/dev/ttyAMA0"
import click

@click.command()
#   @click.option('--baud', required = False, default = 9600, help = 'baud rate defaults to: 9600')
#   @click.option('--port', required = False, default = '/dev/ttyAMA0', help = 'the port to use defaults to: /dev/ttyAMA0')
@click.option('--item', type=(str, int))


def putitem(item):
    click.echo('name=%s id=%d' % item)


def communications():
    """ This checks the baud rate and port to use
    either the command line supplied item or items.
    Or uses the default values
    abaud = 9600 #   default baud rate
    b=abaud
    aport = "/dev/ttyAMA0"
    p=aport
    print(f"abaud = {b} and aport = {p}")
    """

    #   now I wish to check if there were supplied values
    #   on the command line
    #   print(f"Baud supplied {click.option.} port supplied {port}" )

if __name__ == '__main__':
    putitem()       #    communications()

【问题讨论】:

  • 我有我需要的答案:chuffed。

标签: python-3.x parsing command-line command


【解决方案1】:

我用来完成这一切的代码如下,我希望它对某人有所帮助。有更好的方法或错误请指教。

#!/usr/bin/env python3
# -*- coding: utf_8 -*-
import click
from typing import Tuple
#   Command Line test string:  python scratch_2.py -u bbc.co.uk aaa 9600 bbb ccc
myuri = ""      # This is a placeholder for a GLOBAL variable  -- take care!
list1 = []      # This is a placeholder for a GLOBAL variable  -- take care!
@click.command(name="myLauncher", context_settings={"ignore_unknown_options": True})
@click.option('--uri', '-u', type=click.STRING, default=False, help ="URI for the server")
@click.argument('unprocessed_args', nargs = -1, type = click.UNPROCESSED)


def main(uri: str, unprocessed_args: Tuple[str, ...]) -> None:
    #   ====================  Checking the command line structure and obtaining variables
    global myuri                    #   define the use of a GLOBAL variable in this function
    temp = list((str(j) for i in {unprocessed_args: Tuple} for j in i)) # sort out the command line arguments
    res = len(temp)
    # printing result
    print("")
    for e in range(0 ,res):         # list each of the command line elements not including any uri
        print("First check: An input line Tuple element number: " + str(e) +":   " + str(temp[e]))   #    elements base 0
                                    #   ====================  deal with any URI supplied -- or NOT
    if uri is False:                #if  --uri or -u is not supplied
        print("No uri supplied\n")
        print("The input line tuple list elements count: " + str(res))
                                    #   set a defaul GLOBAL value of myuri if it is not supplied
        myuri = "https://192.168.0.90:6691/"        #
    else:
        print("\nThe input line tuple list elements count : " + str(res) + " and we got a uri")
        myuri = uri                 #   set the GLOBAL value of myuri if the uri is
        print(f"which is: {uri}, and therefore myuri also is: {myuri}")     #    a temp print to prove the values of the GLOBAL variable 'myuri'
    #   ==============================================================================================
    #   Testing choice of baud rate on command line
    db_list = {
        '4800': 'TEST48',
        '9600': 'TEST96',
        '19200': 'TEST19',
        '38400': 'TEST38',
        '57600': 'TEST57',
        '115200': 'TEST11',
   }
    # Print databases  ----- db_list ----- listed in dictionary
    print("\nDatabases:")

    for e in range(0 ,res) :
        """ list each of the command line elements not including any uri
        print("Second Check: An input line Tuple element number: " + str(e) +":   " + str(temp[e]))
        elements base 0 """
        if str(temp[e]) in db_list.keys() :
            print(f"The index of db contains {str(temp[e])}, The index refers to: {db_list[str(temp[e])]}")

if __name__ == "__main__":
    # pylint: disable=no-value-for-parameter, unexpected-keyword-arg
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-20
    • 2022-10-02
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2018-09-06
    • 2018-12-17
    • 2018-02-03
    相关资源
    最近更新 更多