views:

51

answers:

2

a lot of command-line .exe applications i use allow you flag optional inputs e.g. program.exe -o outputfile.txt -f F where "-o" indicates an optional output file name different to the default, and where "-F' indicates another option about the script.

so far i've been using the sys.arg[] variables to input file names and such to my python scripts, but that has to be in a set order is it possible to have flagged inputs into python scripts?

[this all comes about because i accidentally put input name and output name in the wrong order and over-wrote my input file]

+6  A: 

If you're using Python 2.7, you want to use argparse. If you're using something older, you want the optparse module.

Velociraptors
+2  A: 

You could use the modules provided by python to handle command line arguments.

How ever this will not remove the issue of inadvertently overwriting your input file. For that, you could put a simple warning that if the output file already exist, proceeding further will overwrite your output file and wait for user input to proceed further. This way at least you can give a chance to stop processing, if you found that the output file name is incorrect.

Something like this :

>>> var = raw_input('Please enter "Y" to proceed further:')
Please enter "Y" to proceed further:Y
>>> var
'Y'
>>>if var == 'Y':
...  sys.exit(0)
... 
pyfunc
thanks, how would i do the warning?
Bec
@Bec: Added it to my reply.
pyfunc