简体   繁体   English

如何知道第三个参数是否传递给脚本?

[英]How to know if third argument is passed to script?

I am working on a script that uses English words for their argument, not the traditional --argument or -a . 我正在编写一个使用英文单词作为其参数的脚本,而不是传统的--argument-a

I have not dare to deal this with argparse, but when I do this with sys.argv like this: 我不敢用argparse来处理这个问题,但是当我用sys.argv这样来做这件事时:

if sys.argv[3]:
    print('yes, there is a third argument')

I get an IndexError: list index out of range . 我收到IndexError: list index out of range What is the possible way to tackle this? 解决这个问题的可能方法是什么? I want to know if there is third argument. 我想知道是否有第三个论点。

You want to check the length of argv : 您要检查argv的长度:

if len(sys.argv) > 3:
    print('yes, there is a third argument')

If you have time, though, it's worth learning argparse. 但是,如果您有时间,值得学习argparse。 It's not too scary, and it makes your code much easier to read. 它不是太吓人,它使您的代码更易于阅读。

You can use len() to check the length first or catch the IndexError . 您可以使用len()首先检查长度或捕获IndexError

if len(sys.argv) > 3:
    # all three arguments are present
    print 'arg1', sys.argv[1], 'arg2', sys.argv[2], 'arg3', sys.argv[3]

or: 要么:

try:
   arg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3]
except IndexError:
   # arguments are missing

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

相关问题 如何知道是否传递了可选参数? - How to know if optional argument was passed? 如果您将文件作为参数传递,python 如何知道在哪里查找文件? - How does python know where to look for a file if you passed it as an argument? 如何找到作为参数传递给Python脚本的配置文件的位置? - How to find the location of the configuration file passed as argument to Python script? 您如何将参数传递给作为参数传递的脚本? - How would you pass arguments to a script being passed as an argument? 知道传递给函数的参数是矢量还是矩阵 - Know whether argument passed to function is a vector or a matrix Linux:如何将命令行参数传递给正在传递给脚本的命令行参数? - Linux:How to pass command line argument to an command line argument that is being passed to a script? python docker 如何打印脚本的返回码以了解测试脚本是通过还是失败 - python docker how to print return code of the script to know if the test script passed or failed 打印一个字符串,次数是传递给脚本的参数的次数 - Print a string as many times as the argument passed to the script 我怎么知道传递给flask_script的管理器的参数 - How can I know the args passed to flask_script's Manager 如何覆盖显式传递的参数 - How to override explicitly passed argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM