4

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.

Robert Baker
  • 167
  • 1
  • 1
  • 14

3 Answers3

10

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
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
3

You may try to use instead of that.

len(sys.argv)
3

sys.argv provides a list of the arguments provided by the command line. The list includes the script being run, as well as any additional arguments. It would look like ['vv.py','optional_argument'] in the case that you provide the argument and ['vv.py'] without it.

import sys     

#Check for volume level input
if len(sys.argv) == 1:
    print(round(volume.value_flat, 2)) 
    exit(0)

#Continue running since exit() wasn't executed
vol = float(sys.argv[1])
Jack Walsh
  • 562
  • 4
  • 14