简体   繁体   English

有没有一种方法可以在 python 中传递 0 命令行 arguments 并且如果传递了特定参数则具有相同的结果?

[英]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.

相关问题 我可以将命令行参数传递给Abaqus python吗? - Can I pass command-line arguments to Abaqus python? 如何将 python 脚本的结果传递给命令行? - How can I pass the result of a python script to the command line? 使用python从命令行传递的json参数无法解码 - json argument passed from the command line with python can't be decoded 我如何从Python列表中获取特定字符,后跟命令行参数变量 - How can i get a particular character from a Python list followed by command line argument variable 通过python中的文件传递命令行参数的最佳方法 - Best way to pass command line arguments via file in python 如果没有传递命令行参数,则为Python默认参数 - Python default parameter if no command line arguments are passed 我可以传递包含'#'的Python命令行参数吗? (没有逃脱?) - Can I pass Python command line arguments which include '#'? (Without escaping?) 如何在Python中将“开始日期”和“结束日期”作为命令行参数传递 - How can I pass “start date” and “end date” as command line arguments in Python Python:命令行参数与硬编码行的传递方式不同 - Python: command line argument not passing the same way as hard coded lines python argh / argparse:如何将列表作为命令行参数传递? - python argh/argparse: How can I pass a list as a command-line argument?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM