[英]Is there a way that I can pass 0 command line arguments in python and have the same result if a particular argument is passed?
I am fairly new to Python.我对 Python 还很陌生。 I need a piece of code to run when either (i) No command line arguments are passed (ii) A particular command line argument, say "help", is passed
当 (i) 没有传递命令行 arguments (ii) 传递特定的命令行参数,比如“帮助”时,我需要一段代码来运行
I have tried working with argparse and sys but I can't seem to get both to work.我曾尝试使用 argparse 和 sys 但我似乎无法让两者都工作。
For the argparse, I tried "default='help'" while adding the argument: parser=add_argument("arg1",default="help")
对于 argparse,我在添加参数时尝试了“default='help'”:
parser=add_argument("arg1",default="help")
For the sys.argv, I tried the following code:对于 sys.argv,我尝试了以下代码:
if (sys.argv[1] == 'help') or not (len(sys.argv) > 1)
But this just gave me an "Index out of range" error.但这只是给了我一个“索引超出范围”错误。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--arg1", default="help")
args = parser.parse_args()
def help():
print("I'm here to help, sorta")
if args.arg1 == "help":
help()
Running this without any command line arguments will output the help message.在没有任何命令行 arguments 的情况下运行此命令将 output 帮助消息。 Running this with
python3 program.py --arg1 help
(assuming this code is in the file program.py) will also output the help message.使用
python3 program.py --arg1 help
运行它(假设此代码在文件 program.py 中)也将 output 帮助消息。 Finally, running python3 program.py --arg1 nohelp
will not output the help message (not just 'nohelp', but anything other than 'help').最后,运行
python3 program.py --arg1 nohelp
不会 output 帮助消息(不仅仅是“nohelp”,而是“help”以外的任何内容)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.