Skip to main content
 首页 » 编程设计

python之如何使 python 脚本在有参数和无参数(默认参数)的情况下工作

2025年05月04日14lautakyan007

我正在尝试让 Python 脚本工作,无论参数是否已传递。

目标是使脚本像“MyPython.py”一样运行,“MyPython.py 5”应该能够运行。如果未传递任何参数,则参数应为 0。

变量 imported_number 默认情况下应为 0,但如果检测到参数,则它应采用用户传递的任何数字。

import argparse 
 
imported_number=0 
 
parser = argparse.ArgumentParser() 
parser.add_argument("opt_number", type=int, help="Provide a number please") 
args = parser.parse_args() 
 
if args.opt_number > 0: 
    imported_number=args.opt_number 
    print "You provided me with the number " + imported_number 
    print "You provided me with the number {}".format(args.opt_number) 
else: 
    print "You did not provide me with any number. Taking the default value, which is " + imported_number 

不幸的是,我收到了error: too few arguments 错误消息。

有谁知道完成这项任务的好的自动化方法吗?我将不胜感激。

请您参考如下方法:

像这样使用 nargs、default、const:

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument("opt_number", type=int, help="Provide a number please", 
                    nargs='?', default=0, const=0) 
args = parser.parse_args() 
print(args) 

如果没有提供参数,您的 opt_number 将被初始化为 0。