user986959
user986959

Reputation: 630

Parse command line argument

Some of you might know this script, it's called 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.

Upvotes: 0

Views: 261

Answers (3)

Nick Beeuwsaert
Nick Beeuwsaert

Reputation: 1638

the preferred method is to use 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:

#!/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);

Upvotes: 2

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

You can either use sys.argv[0] to get the first command line argument to the script. Or the argparse module if you want more options.

Upvotes: 0

user986959
user986959

Reputation: 630

Ok, after I imported sys, the only thing I need to do is pass the sys.argv to the variable being printed. Example:

variable = sys.argv
print variable

Upvotes: 0

Related Questions