【发布时间】:2020-06-22 04:28:13
【问题描述】:
我正在制作一个程序,其中click 模块用于解析命令行参数。
-r 和 -t 参数应该传递给第一个函数,-f 和 -l 应该传递给第二个函数。
我通过命令行参数提供了以下输入,但它不接受第二个函数的输入并给出“额外参数”之类的错误。
如何使用click 模块的多种功能?
输入:
PS D:\FinIQ\LoadTest> python ram.py -r 80 -t 10 --firstname john --lastname doe
Usage: ram.py [OPTIONS]
Try 'ram.py --help' for help.
Error: Got unexpected extra arguments (john doe)
TypeError: LoadMemory() got an unexpected keyword argument 'firstname'
import sys, psutil
from multiprocessing import Pool
from multiprocessing import cpu_count
from psutil import virtual_memory
import time
from functools import partial
import click
@click.command()
@click.option("--mempercent", "-r",default=70, prompt="how much ram you want to consume:" ,help="RAM %:")
@click.option("--timesec","-t", prompt="time for which ram to be consumed:",
help="enter time in seconds")
@click.option("--firstname", "-f" , prompt="enter firstname" ,help="firstname")
@click.option("--lastname", "-l", prompt="enter lastname" ,help="lastname")
def LoadMemory(mempercent, timesec):
currentMemory = virtual_memory().percent
print('Current utilized memory = ', currentMemory, "%")
while mempercent <= currentMemory:
print('Already utilzed! ')
print('How much memory to be stressed(%)?')
mempercent = int(input())
MemToFillMore = int(mempercent - currentMemory)
new_list = [0] * 10485760 * MemToFillMore
print('After loading memory utilized=', virtual_memory().percent, "%")
timeint = int(timesec)
time.sleep(timeint)
new_list.clear()
print('After clearing memory utilized=', virtual_memory().percent, "%")
def name(firstname, lastname):
print("full name is:" + firstname + " " + lastname)
if __name__ == '__main__':
LoadMemory()
name()
【问题讨论】:
-
您需要创建一个接受所有这些参数的函数,然后该函数将使用适当的参数调用适当的函数。
-
也许你应该使用@click和函数
myfunction(mempercent, timesec, firstname, lastname):,它应该运行LoadMemory(mempercent, timesec)和name(firstname, lastname)
标签: python command-line command-line-arguments python-click