john john - 2 months ago 23
Python Question

issue regarding sys.argv and batch file

#! /usr/bin/python3
# pw.py - An insecure password locker program.

PASSWORDS = {'email': 'aklsjdlksajdkljl',
'blog': 'dklasjkl9379343',
'luggage': '12345'}

import sys, pyperclip


if len(sys.argv) < 2:
print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
sys.exit()

account = sys.argv[1] # first command line arg is the account name


if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + " " + sys.argv[0] + " " + sys.argv[1] + ' copied to clipboard.')
else:
print('There is no account named ' + account)


When I type
./pw.py email
in terminal, it will go straight to the line:
if account in PASSWORDS:
and will skip line:
if len(sys.argv) < 2:


Why did it skip that line?

Answer

If sys.argv[1] is defined, the length of sys.argv is 2 or greater. The test sys.argv < 2 is only going to be true when sys.argv contains just 0 or 1 items. So the if len(sys.argv) < 2: is not skipped, the test is just false and the associated block is not executed.

sys.argv[0] is always set to the script name (here pw.py), so the length would be at least 1.

Note that you just used python pw.py (so no account or other arguments), you'd get an index error, as the following line tries to index to sys.argv[1], a value that is not set:

print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
# This raises an index error when len(sys.argv) < 2   ^^^