简体   繁体   English

解析命令行参数

[英]Parse command line argument

Some of you might know this script, it's called hash-identifier . 有些人可能知道这个脚本,它叫做hash-identifier When it is run the user is prompted to enter a hash. 运行时,系统会提示用户输入哈希值。 I want to pass the hash as a command line argument so that the script can be executed like that: 我想将哈希作为命令行参数传递,以便脚本可以像这样执行:

hash-identifier d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f

I found out that I need to import sys and getopt but I have never used python before so any suggestions would be helpful. 我发现我需要导入sys和getopt,但我之前从未使用过python,所以任何建议都会有所帮助。

the preferred method is to use argparse: 首选方法是使用argparse:

#!/usr/bin/env python
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Does something with a hash");
    parser.add_argument("hash", metavar="HASH", help="the hash to do things with?");

    args = parser.parse_args();

    hash = args.hash;

    # Use the hash...
    print(hash);

But using argparse might be a bit overkill for your needs, it may be simpler for you to do this: 但是使用argparse可能对你的需求有点过分,你可能更容易做到这一点:

#!/usr/bin/env python

import sys

if __name__ == "__main__":
    if len(sys.argv) != 2: # first is program name, second is argument
        print("USAGE: %s HASH"%(sys.argv[0],));
        sys.exit();
    hash = sys.argv[1];

    # Use the hash...
    print(hash);

Ok, after I imported sys, the only thing I need to do is pass the sys.argv to the variable being printed. 好吧,在我导入sys之后,我唯一需要做的就是将sys.argv传递给正在打印的变量。 Example: 例:

variable = sys.argv
print variable

You can either use sys.argv[0] to get the first command line argument to the script. 您可以使用sys.argv[0]获取脚本的第一个命令行参数。 Or the argparse module if you want more options. 或者argparse模块,如果你想要更多选项。

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

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