I need to add a commandline parameter to a python file (I don't have functions defined inside) so that the parameter would be platform, and then inside the file I need to use:
if platform == iphone:
<execute some code>
elif platform == ipad:
<execute some other code>
Basically whats defined under if and elif is the same code but using different resources (images, txt files, etc.). What I need is the possibility to run that file from commandline with the platform parameter like:
python somefile.py -iphone
Now I tried with argparse like that:
platform = argparse.ArgumentParser()
platform.add_argument("iphone")
platform.add_argument("ipad")
platform.parse_args()
But clearly it is wrong and/or is missing something because it doesn't work at all. I'm looking for a simplest possible way to achieve that.
if you pass command as python somefile.py iphone
then you can get the arguments passed in terminal with sys.argv
.
It gives a list of arguments passed with command. In your case sys.argv
will return ['somefile.py','iphone'] i.e 0th position will contain program name and from 1st place onwards all the arguments passed.
import sys
platform=sys.argv[1]
if platform == 'iphone':
<execute some code>
elif platform == 'ipad':
<execute some other code>