Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optparse and sys.argv - Python

Tags:

python

linux

i've written a python script, that accepts input via the optparse module of python. and I take input from sys.argv as well.

When I use either of them, the program works correctly. For example:

python dperf.py -m 1 -c 2 -n 3
python dperf.py foobar 

However, it does not when I give the input in this manner.

python dperf.py foobar -m 1 -c 2 -n 3

Is there a mistake in the way I am using sys.argv?

parser = optparse.OptionParser()
#migration
parser.add_option("-m", type="float", dest="migr")
#collection
parser.add_option("-c", type="float", dest="coll")
#num of lines to read
parser.add_option("-n", type="float", dest="fileread")
(options, args) = parser.parse_args()

ti =  options.migr
colle =  options.coll
linereadfiles =  options.fileread

apps = sys.argv[1:]
like image 323
pistal Avatar asked Jul 17 '26 14:07

pistal


1 Answers

If you parse options via the parse_args() of the OptionParser, do not use sys.argv directly but the returned args instead which should contain the parts not already parsed by the OptionParser.

For example in your code replace

 apps = sys.argv[1:]

by

apps = args

(or just scrap the apps and go on with args).

like image 164
Clemens Klein-Robbenhaar Avatar answered Jul 20 '26 03:07

Clemens Klein-Robbenhaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!