ageoff
ageoff

Reputation: 2828

Python: Compare sys.argv with a string

This seems like it should be so simple, but i am having some serious issues. All i want to do is see if the user input matches a 2 letter expression. I guess my biggest problem i have is that i am not very familiar with the re library and the documentation does not really help me too much.

This is what i have tried so far:

try 1

if re.match(sys.argv[3],  "GL",  re.I):
    input_file_path = "V:\\test"

try 2

if re.ignorecase(sys.argv[3],  "GL"):
    input_file_path = "V:\\test"

try 3

if sys.argv[3] == "GL":
    input_file_path = "V:\\test"

The way i call the program to run: filename.py tester test GL "tester" and "test" are not really used yet.

EDIT: I found my main problem. I was calling a bunch of if statements rather than elif. So the last one that said else: exit() always got hit (cause i was testing the first if). rookie mistake

Upvotes: 0

Views: 6782

Answers (3)

bukzor
bukzor

Reputation: 38462

Obviously the third argument is not 'GL'. print sys.argv and you will see that. My guess is that you are off by one in your index.

Show us the commandline you use to run your script.


printing the sys.argv[3] prints exactly GL – LiverpoolFTW


Then the bug is elsewhere. If you print sys.argv[3].lower() == "gl" just before, and input_file_path just after, you will see the expected values. What you really need here is a debugger. pdb is the built-in standard, but I highly recommend pudb.

For quick setup, paste these into a terminal. virtualenv is a industry standard for keeping project dependencies separate.

cd ~
wget https://raw.github.com/pypa/virtualenv/1.6.3/virtualenv.py
python virtualenv.py mypy
source mypy/bin/activate
pip install pudb

Source that activate file whenever you want to get into the environment. Run deactivate (an alias defined by activate) to get out. Make sure to use the python in the environment (ie #!/usr/bin/env python) rather than hard-coding a particular python instance.

Upvotes: 0

Gautam Raj
Gautam Raj

Reputation: 199

Your re.match is backward. The pattern comes first. Try:

if re.match('GL', sys.argv[3], re.I):
    input_file_path = "V:\\test"

Upvotes: 1

orlp
orlp

Reputation: 117661

Just convert the string to test to lowercase before comparing and you should be fine:

if sys.argv[3].lower() == "gl":
    input_file_path = "V:\\test"

More notably, regular expressions are not the right tool for this job.

Upvotes: 6

Related Questions