简体   繁体   English

检查 sys.argv[x] 是否已定义

[英]Checking if sys.argv[x] is defined

What would be the best way to check if a variable was passed along for the script:检查是否为脚本传递了变量的最佳方法是什么:

try:
    sys.argv[1]
except NameError:
    startingpoint = 'blah'
else:
    startingpoint = sys.argv[1]

Check the length of sys.argv :检查sys.argv的长度:

if len(sys.argv) > 1:
    blah = sys.argv[1]
else:
    blah = 'blah'

Some people prefer the exception-based approach you've suggested (eg, try: blah = sys.argv[1]; except IndexError: blah = 'blah' ), but I don't like it as much because it doesn't “scale” nearly as nicely (eg, when you want to accept two or three arguments) and it can potentially hide errors (eg, if you used blah = foo(sys.argv[1]) , but foo(...) raised an IndexError , that IndexError would be ignored).有些人更喜欢你建议的基于异常的方法(例如, try: blah = sys.argv[1]; except IndexError: blah = 'blah' ),但我不太喜欢它,因为它不“缩放”几乎一样好(例如,当您想要接受两个或三个参数时)并且它可能隐藏错误(例如,如果您使用blah = foo(sys.argv[1]) ,但是foo(...)引发了一个IndexError ,该IndexError将被忽略)。

In the end, the difference between try, except and testing len(sys.argv) isn't all that significant.最后, try, except和 testing len(sys.argv)之间的区别并不是那么重要。 They're both a bit hackish compared to argparse .argparse相比,它们都有点hackish。

This occurs to me, though -- as a sort of low-budget argparse:不过,这发生在我身上——作为一种低预算的 argparse:

arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))

You could even use it to generate a namedtuple with values that default to None -- all in four lines!您甚至可以使用它来生成一个namedtuple ,其值默认为None —— 全部在四行中!

Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))

In case you're not familiar with namedtuple , it's just a tuple that acts like an object, allowing you to access its values using tup.attribute syntax instead of tup[0] syntax.如果您不熟悉namedtuple ,它只是一个充当对象的元组,允许您使用tup.attribute语法而不是tup.attribute tup[0]语法访问其值。

So the first line creates a new namedtuple type with values for each of the values in arg_names .因此,第一行创建了一个新的namedtuple类型,其中包含arg_names每个值的值。 The second line passes the values from the args dictionary, using get to return a default value when the given argument name doesn't have an associated value in the dictionary.第二行传递args字典中的值,当给定的参数名称在字典中没有关联值时,使用get返回默认值。

Another way I haven't seen listed yet is to set your sentinel value ahead of time.我还没有看到列出的另一种方法是提前设置您的哨兵值。 This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an else statement.这种方法利用了 Python 的惰性求值,您不必总是在其中提供else语句。 Example:例子:

startingpoint = 'blah'
if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]

Or if you're going syntax CRAZY you could use Python's ternary operator :或者,如果您要语法 CRAZY,则可以使用 Python 的三元运算符

startingpoint = sys.argv[1] if len(sys.argv) >= 2 else 'blah'

I use this - it never fails:我使用这个 - 它永远不会失败:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

It's an ordinary Python list.这是一个普通的 Python 列表。 The exception that you would catch for this is IndexError, but you're better off just checking the length instead.您会为此捕获的异常是 IndexError,但您最好只检查长度。

if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]
else:
  startingpoint = 'blah'

Pretty close to what the originator was trying to do.非常接近发起者试图做的事情。 Here is a function I use:这是我使用的一个函数:

def get_arg(index):
    try:
        sys.argv[index]
    except IndexError:
        return ''
    else:
        return sys.argv[index]

So a usage would be something like:所以用法是这样的:

if __name__ == "__main__":
    banner(get_arg(1),get_arg(2))

A solution working with map built-in fonction !使用地图内置功能的解决方案!

arg_names = ['command' ,'operation', 'parameter']
args = map(None, arg_names, sys.argv)
args = {k:v for (k,v) in args}

Then you just have to call your parameters like this:然后你只需要像这样调用你的参数:

if args['operation'] == "division":
    if not args['parameter']:
        ...
    if args['parameter'] == "euclidian":
        ...

You can simply append the value of argv[1] to argv and then check if argv[1] doesn't equal the string you inputted Example:您可以简单地将 argv[1] 的值附加到 argv,然后检查 argv[1] 是否不等于您输入的字符串示例:

from sys import argv
argv.append('SomeString')
if argv[1]!="SomeString":
            print(argv[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM