0

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.

2 Answers2

1

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>
Pratik Kumar
  • 2,211
  • 1
  • 17
  • 41
  • Ok, this one works, but I came up with another idea, if it is possible to add another argument that way, that would be passed into a variable. F.e. I run _python somefile.py -iphone -2.20.0_ so that the second parameter is version and is saved into a variable inside this file? – Witold Dołowicz Feb 02 '18 at 10:35
  • Ok, nevermind. I did that :) Second one would be: version = sysargv[2] and I pass that variable/parameter to a function that puts that second parameter as string exactky where I need it. – Witold Dołowicz Feb 02 '18 at 11:01
0

If you want to use ArgumentParser you need to change your code to:

parser= argparse.ArgumentParser()
parser.add_argument("-platform")
args = parser.parse_args()

if args.platform == 'iphone'
    ##do something with that information 

useage:

python somefile.py -platform iphone

read more about argParser here

otherwise you could simply use sys.argv[1] :

import sys 
if sys.argv[1] == 'iphone':
    # iphone

useage for sys.argv:

python somefile.py iphone
Tim
  • 10,459
  • 4
  • 36
  • 47