Python 如何检查命令行中的参数是否已设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4188467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:42:07  来源:igfitidea点击:

How to check if an argument from commandline has been set?

python

提问by Richard Knop

I can call my script like this:

我可以这样调用我的脚本:

python D:\myscript.py 60

And in the script I can do:

在脚本中我可以这样做:

arg = sys.argv[1]
foo(arg)

But how could I test if the argument has been entered in the command line call? I need to do something like this:

但是如何测试参数是否已在命令行调用中输入?我需要做这样的事情:

if isset(sys.argv[1]):
    foo(sys.argv[1])
else:
    print "You must set argument!!!"

采纳答案by Katriel

Don't use sys.argvfor handling the command-line interface; there's a module to do that: argparse.

不要sys.argv用于处理命令行界面;有一个模块,这样做:argparse

You can mark an argument as required by passing required=Trueto add_argument.

您可以通过传递required=True到 来根据需要标记参数add_argument

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("foo", ..., required=True)
parser.parse_args()

回答by J V

if(sys.argv[1]):should work fine, if there are no arguments sys.argv[1] will be (should be) null

if(sys.argv[1]):应该可以正常工作,如果没有参数 sys.argv[1] 将(应该)为空

回答by khachik

len(sys.argv) > 1

len(sys.argv) > 1

回答by chris

if len(sys.argv) < 2:
    print "You must set argument!!!"

回答by DNS

If you're using Python 2.7/3.2, use the argparsemodule. Otherwise, use the optparsemodule. The module takes care of parsing the command-line, and you can check whether the number of positional arguments matches what you expect.

如果您使用的是 Python 2.7/3.2,请使用该argparse模块。否则,使用optparse模块。该模块负责解析命令行,您可以检查位置参数的数量是否符合您的预期。

回答by Rafi

I use optparse modulefor this but I guess because i am using 2.5 you can use argparse as Alex suggested if you are using 2.7 or greater

我为此使用optparse 模块,但我想是因为我使用的是 2.5,如果您使用的是 2.7 或更高版本,您可以按照 Alex 的建议使用 argparse

回答by Valentinos Ioannou

for arg in sys.argv:
    print (arg)  
    #print cli arguments

You can use it to store the argument in list and used them. Is more safe way than to used them like this sys.argv[n]

您可以使用它将参数存储在列表中并使用它们。比这样使用它们更安全sys.argv[n]

No problems if no arguments are given

如果没有给出参数就没有问题

回答by Miguel Armenta

if len(sys.argv) == 1:
   print('no arguments passed')
   sys.exit()

This will check if any arguments were passed at all. If there are no arguments, it will exit the script, without running the rest of it.

这将检查是否传递了任何参数。如果没有参数,它将退出脚本,而不运行它的其余部分。