Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling an empty (sys.argv[1]) [duplicate]

I am writing a script that controls volume. The name of the script is vv , and it expects one argument. for example vv .9 where .9 is the level you want to set the volume. That program works as expected, but I want to change it so that if the argument is omitted, it prints out the current volume level. I have tried to write it this way.

import sys 
vol = float(sys.argv[1])

if len(sys.argv[1]) == 0:
    print(round(volume.value_flat, 2)) 
    exit(0)

else:
    run the rest of the program

I've also tried it this way:

if (sys.argv[1]) == '':

both of those ways fail. I guess if sys.argv doesn't get it's argument, it's not going to run the program, even if you specifically test for no argument? Is there a better way to do this without using argparse?

update: I fixed this with the help of a couple of the answers. The first thing I was doing wrong was testing for len == 0 rather than len == 1. sys.argv will never have a len of 0 because the script name is always [0]. the other thing was that I was working on sys.argv before testing len - apparently that's a no - no. Also, my syntax was wrong, should have been using (sys.argv) rather than (sys.argv[1]).

Here is the updated code:

if len(sys.argv) == 1:
    with Pulse('volume-example') as pulse:
        sink_input = pulse.sink_input_list()[0] 
        volume = sink_input.volume
        print('current level:','\t', round(volume.value_flat, 2)) 
        exit(0)

 else:
    vol = float(sys.argv[1]) # this line had to be moved to after len was checked

thanks to everyone that helped. I think I needed all three answer to fix it.

like image 279
Robert Baker Avatar asked Oct 16 '25 07:10

Robert Baker


2 Answers

sys.argv is a list that contains the program's arguments, with sys.argv[0] being the name of the script itself.

The way to count how many arguments there are is to check the length of sys.argv, not of sys.argv[1].
You also need to do this before trying to access sys.argv[1], since it might not exist:

import sys 

if len(sys.argv) < 2:
    print(round(volume.value_flat, 2)) 
    exit(0)

vol = float(sys.argv[1])

# run the rest of the program
like image 53
molbdnilo Avatar answered Oct 17 '25 21:10

molbdnilo


You may try to use instead of that.

len(sys.argv)
like image 28
Yoshitha Penaganti Avatar answered Oct 17 '25 22:10

Yoshitha Penaganti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!