views:

224

answers:

6

Hi,

I want to test againts multiple command line arguments in a loop

> python Read_xls_files.py group1 group2 group3

No this code tests only for the first one (group1).

hlo = []
for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value == sys.argv[1]:
      hlo.append(sh.cell(i, 8).value)

How should I modify this that I can test against one, two or all of these arguments? So, if there is group1 in one sh.cell(i, 1), the list is appended and if there is group1, group2 etc., the hlo is appended.

+2  A: 

You can iterate over sys.argv[1:], e.g. via something like:

for grp in sys.argv[1:]:
  for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value == grp:
      hlo.append(sh.cell(i, 8).value)
Stephen Doyle
You want to iterate over `sys.argv[1:]`, not `sys.argv`; you don't want to include `argv[0]`, which is the name of script being run.
Adam Rosenfield
+1  A: 

I would recommend taking a look at Python's optparse module. It's a nice helper to parse sys.argv.

Bartek
A: 

I believe this would work, and would avoid iterating over sys.argv:

hlo = []
for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value in sys.argv[1:]:
      hlo.append(sh.cell(i, 8).value)
Graeme Perrow
Thaks, this was very useful, and quicker solution
jrara
Changed `argv` to `argv[1:]` - see Adam's comment on Stephen's answer.
Graeme Perrow
+3  A: 
outputList = [x for x in values if x in sys.argv[1:]]

Substitute the bits that are relevant for your (spreadsheet?) situation. This is a list comprehension. You can also investigate the optparse module which has been in the standard library since 2.3.

cjrh
+1  A: 

argparse is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.

mavnn
A: 
# First thing is to get a set of your query strings.
queries = set(argv[1:])
# If using optparse or argparse, queries = set(something_else)
hlo = []
for i in range(len(sh.col_values(8))):
    if sh.cell(i, 1).value in queries:
        hlo.append(sh.cell(i, 8).value)

=== end of answer to question ===

Aside: the OP is using xlrd ... here are a couple of performance hints.

Doesn't matter too much with this simple example, but if you are going to do a lot of coordinate-based accessing of cell values, you can do better than that by using Sheet.cell_value(rowx, colx) instead of Sheet.cell(rowx, colx).value which builds a Cell object on the fly:

queries = set(argv[1:])
hlo = []
for i in range(len(sh.nrows)): # all columns have the same size
    if sh.cell_value(i, 1) in queries:
        hlo.append(sh.cell_value(i, 8))

or you could use a list comprehension along with the Sheet.col_values(colx) method:

hlo = [
    v8
    for v1, v8 in zip(sh.col_values(1), sh.col_values(8))
    if v1 in queries
    ]
John Machin