Elsa
Elsa

Reputation: 307

How to use sys.argv in python to check length of arguments so it can run as script?

Ok so here is part of my code (I have imported sys)

if __name__ == '__main__':


MyCaesarCipher = CaesarCipher() #MyCaesarCipher IS a CaesarCipher()

if len(sys.argv) >1:
    #what will it check? 

Done = False   
while not Done:
    print('C Clear All')
    print('L Load Encrypted File')
    print('R Read Decrypted File')
    print('S Store Encrypted File')
    print('W Write Decrypted File')
    print('O Output Encrypted Text')
    print('P Print Decrypted Text')
    print('E Encrypt Decrypted Text')
    print('D Decrypted Encrypted Text')
    print('Q Quit')
    print('----------------')
    print('Enter Choice>')

So the thing is I want to do is if the command line length is more than 1, the program runs as a script.

This is the instruction:

If no command line arguments are input, then the script enters menu mode. If more than 1 command line argument (anything other than script name) is provided during the run of the script it enters single run mode.

I do not know what this means, though.

Upvotes: 7

Views: 60961

Answers (5)

Vivek Sable
Vivek Sable

Reputation: 10213

What is sys.arvg:

The list of command line arguments passed to a Python script. argv[0] is the script name.

Demo: File Name: 1.py

import sys

if __name__=="__main__":
    print "command arguments:", sys.argv 

Output:

$ python 1.py arg1 arg2 
command arguments: ['1.py', 'arg1', 'arg2']
$ python 1.py
command arguments: ['1.py']

Your problem is, we have to run code by Command Line Argument and by Menu also.

When User provided the Enter Choice from the command line then use provided value to next process.

If User not provided the Enter Choice from the command line then ask User to Enter Choice from the Menu.

Demo:

File Name: 1.py

import sys

if __name__ == '__main__':
    try:
        arg_command = sys.argv[1]
    except IndexError:
        arg_command = ""

    Done = False
    while not Done:
        if arg_command=="":
            print('\nMenu')
            print('C Clear All')
            print('L Load Encrypted File')
            print('Q Quit')
            print('----------------')
            print('Enter Choice>')
            command = raw_input('Enter Selection> ').strip()[0].upper()
        else:
            command = arg_command
            #- set arg value to empty to run Menu option again.
            arg_command = ""

        if command == 'C':
            print "In Clear All event."
        elif command == 'L':
            print "In Clear All event."
        elif command == "Q":
            break
        else:
            print "Wrong Selection."

Output:

Enter Choice given from the Command Line:

$ python 1.py C
In Clear All event.

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$ 

No Command Line argument.

$ python 1.py

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> l
In Clear All event.

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$ 

Upvotes: 10

caynan
caynan

Reputation: 139

First of all you have to understand what argv is, try creating this script, and call it learning_argv.py

import sys

print(sys.argv)

now try running the script like this:

$ python3 learning_argv.py
$ python3 learning_argv.py a
$ python3 learning_argv.py a b c
$ python3 learning_argv.py AWESOME TEXT

See what argv is?

What you're doing when you test if the length of argv is bigger than one, is basically testing if you're receiving anything beyond the script name.

In the future, you could create a similar structure you created for your menu, to treat arguments sent directly from the command line.

take a look at this quick tutorial in order to better understand argv.

Upvotes: 1

Since you seem to be pretty new to python here's a simple example using your code. You'll have to complete the menu and the actual code for the menu options but it does use sys.argv

import sys

def menu():
    Done = False   
    while not Done:
        print('C Clear All')
        print('L Load Encrypted File')
        print('R Read Decrypted File')
        print('S Store Encrypted File')
        print('W Write Decrypted File')
        print('O Output Encrypted Text')
        print('P Print Decrypted Text')
        print('E Encrypt Decrypted Text')
        print('D Decrypted Encrypted Text')
        print('Q Quit')
        print('----------------')
        print('Enter Choice>') #should get user input here
        Done = True

if __name__=="__main__" :
    if len(sys.argv) > 1 : 
    #Here if an argument is present run it or load the menu
        print "run whatever option was entered on the commandline"
    else:
        menu()

Upvotes: 2

yxre
yxre

Reputation: 3704

The instructions want the script to use the command line arguments to execute the script.

python script.py [arg1] [arg2] [arg3] ....

The args are accessible through sys.argv.

sys.argv = ['script.py', '[arg1]', '[arg2]', '[arg3]']

You will need to use a command line interface instead of the menu interface when args are present.

Upvotes: 3

erewok
erewok

Reputation: 7835

Here's the thing, when you're learning a language like this, you can often get by pretty well with just printing out things you don't really understand.

Try this:

Step 1) Make a program that looks like this:

import sys
if __name__ == '__main__':
    for idx, arg in enumerate(sys.argv):
       print("arg #{} is {}".format(idx, arg))
    print len(sys.argv)

After that, run your program from the command line like this:

$ python3 test_script.py

Then, run it like this:

$ python3 test_script.py somearg someother andanother etc "23908452359"

What you discover may be useful to perform this task you are looking to resolve.

Lastly, "menu mode" sounds like the script is going to take input from the user. Thus, you'll need to use input() to do that. It also sounds like you need to come to some decision about when to use menu mode or not, which you've already started to do with your if-test above.

Experiment a bit, though, and you'll figure it out.

Upvotes: 3

Related Questions