Search code examples
pythonargv

sys.argv ussage in python


I was just wondering how to use in this specific program the sys.argv list for command line arguments instead of the input method. As argc does not exist in python, the length will be determent with the len method, right?

Thanks for any help in advance!

MORSE_CODE_DICT = {
    'A':'.-',
    'B':'-...',
    'C':'-.-.',
    'D':'-..',
    'E':'.',
    'F':'..-.',
    'G':'--.',
    'H':'....',
    'I':'..',
    'J':'.---',
    'K':'-.-',
    'L':'.-..',
    'M':'--',
    'N':'-.',
    'O':'---',
    'P':'.--.',
    'Q':'--.-',
    'R':'.-.',
    'S':'...',
    'T':'-',
    'U':'..-',
    'V':'...-',
    'W':'.--',
    'X':'-..-',
    'Y':'-.--',
    'Z':'--..',
    '1':'.----',
    '2':'..---',
    '3':'...--',
    '4':'....-',
    '5':'.....',
    '6':'-....',
    '7':'--...',
    '8':'---..',
    '9':'----.',
    '0':'-----',
}

```python

def encryptor(text):
    encrypted_text = ""
    for letters in text:
        if letters != " ":
            encrypted_text = encrypted_text + MORSE_CODE_DICT.get(letters) + " "
        else:
            encrypted_text += " "
    print(encrypted_text)

text_to_encrypt = input("Enter Some Text To Encrypt : ").upper()
encryptor(text_to_encrypt)


Solution

  • The first element of sys.argv is the name of the executing program. The remaining are the parameters passed to the program, as managed by the shell. For instance, with file name expansion *.txt will expand into a separate element for each text file found. You can write a test program to see different expansions

    test.py:

    import sys
    print(sys.argv)
    

    Two ways to run that would be

    $ python test.py hello there buckaroo
    ['test.py', 'hello', 'there', 'buckaroo']
    $ python test.py "hello there buckaroo"
    ['test.py', 'hello there buckaroo']
    

    An easy solution for you is to just concatenate the arguments so that a person can input with or without quotes

    import sys
    text_to_encrypt = " ".join(sys.argv[1:]).upper()
    encryptor(text_to_encrypt)
    

    Adding that code we get

    $ python morsecoder.py hello there buckaroo
    .... . .-.. .-.. ---  - .... . .-. .  -... ..- -.-. -.- .- .-. --- --- 
    

    Notice we don't need to know the length of argv specifically. Python likes to iterate - its often the case that if you need the length of something, you are doing it wrong.