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.