Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command line arguments in python script

Tags:

python

shell

I have a program that is run from the command line like this

python program.py 100 rfile

How can I write a new script so that instead of running it with just the '100' argument, I can run it consecutively with a list of arguments like [50, 100, 150, 200]?

Edit: The reason I am asking is that I want to record how 'program.py' executes with different arguments.

like image 292
Chris Avatar asked Oct 15 '10 03:10

Chris


2 Answers

If you create a bash file like this

#!/bin/bash
for i in 1 2 3 4 5
do
  python program.py $i rfile
done

then do chmod +x on that file, when you run it, it will run these consecutively:

python program.py 1 rfile
python program.py 2 rfile
python program.py 3 rfile
python program.py 4 rfile
python program.py 5 rfile
like image 123
Devrim Avatar answered Oct 06 '22 14:10

Devrim


You can use Devrim's shell approach or you can modify your script:

If your original script worked like this:

import sys
do_something(sys.argv[1], sys.argv[2])

You could accomplish what you want like this:

def main(args):
    for arg in args[:-1]:
        do_something(arg, args[-1])

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

You would invoke it like so:

python program.py 50 100 150 200 rfile

I'm guessing at what you want. Please clarify if this isn't right.

like image 29
Jon-Eric Avatar answered Oct 06 '22 12:10

Jon-Eric