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

5

7

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.

Baranowski answered 14/3, 2015 at 5:24 Comment(0)
D
10

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
$ 
Dogged answered 14/3, 2015 at 17:44 Comment(0)
A
3

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.

Anti answered 14/3, 2015 at 5:31 Comment(3)
Thanks for your reply, we have to use menu mode, and yes I have written if else statements and inputs below the menu. So I am confused on what to do?Baranowski
I read here pythonforbeginners.com/argv/more-fun-with-sys-argv but I still do not understandBaranowski
If you tried the example I gave above, you would be able to answer one relevant question, namely: "How many command line arguments" amounts to "no command-line arguments". In other words, what's the len(sys.argv) when you run your script without any arguments? Give that part a shot. One thing a time, in other words.Anti
R
3

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.

Renelle answered 14/3, 2015 at 5:31 Comment(2)
So would I need to write anything in the code? Or do I write that in CMDBaranowski
The python script needs to know how to interpret the information from CMD. If I call your script with ['e' ,'filename.txt'], then it should encrypt the file. Or whatever scheme you want to use. This is probably an exercise in modularity and code reuse. The part of your program that does the work needs to be separate from the UI component whether its an interactive menu or command line interface.Renelle
A
2

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()
Atrium answered 14/3, 2015 at 5:42 Comment(0)
C
1

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.

Claribel answered 14/3, 2015 at 5:53 Comment(3)
do i run the script on the CMD?Baranowski
The line $ python3 learning_argv.py I'm AWESOME isn't going to like that apostrapheJasun
Yeah @Elsa, Every time you see a $ before some commands, it usually means that the things after that must be executed in the command line. So in this case, go to your terminal, navigate to the folder on which you saved the script and run the commands.Claribel

© 2022 - 2024 — McMap. All rights reserved.