-2

I am trying to get parameters from the command line to initialize the following class

import sys


class Test(object):

    def __init__(self):
        for item in sys.argv:
            if item.startswith("-Username"):
                self.Username = item.split("Username=", 1)[1]
            if item.startswith("-SessionID"):
                self.sessionID = item.split("SessionID=", 1)[1]
            if item.startswith("-appName"):
                self.appName = item.split("appName=", 1)[1]

    def run(self):
       msg = '''Username {0} with SessionID {1} is using the {2} app.'''.format(self.Username, self.SessionID, self.appName)
       print msg

if __name__ == '__main__':
Test().run()

In the command line I execute:

python test.py -Username=AAA, -SessionID=223, -appName=ABC

which gives the following error:

AttributeError: 'Test' object has no attribute 'Username'.

I wonder why is that? Any help is appreciated.

Sepehr
  • 442
  • 1
  • 6
  • 17
  • It will only have `self.Username` `if item.startswith("-Username")`. It isn't set otherwise. – Peter Wood Jan 06 '16 at 15:47
  • 1
    This problem isn't anything to do with handling command line arguments. – Peter Wood Jan 06 '16 at 15:48
  • 1
    Maybe you've some case problem? There's sessionID and SessionID, besides this everything works for me. – dfranca Jan 06 '16 at 15:51
  • 3
    This is not an attempt to answer your question -- But it will probably save you some headaches later on if you use a commandline parsing library (`argparse` is good and comes in the stdlib) and if you separate the commandline parsing from the class. – mgilson Jan 06 '16 at 16:08

1 Answers1

0

It is a matter of inconsistency in variable naming. If the capitalization problems are fixed, code works as expected:

import sys

class Test(object):

  def __init__(self):
    for item in sys.argv:
      if item.startswith("-Username"):
        self.Username = item.split("Username=", 1)[1]
      if item.startswith("-SessionID"):
        self.sessionID = item.split("SessionID=", 1)[1]
      if item.startswith("-appName"):
        self.appName = item.split("appName=", 1)[1]

  def run(self):
   msg = '''Username {0} with SessionID {1} is using the {2} app.'''.format(self.Username, self.sessionID, self.appName)
   print msg

if __name__ == '__main__':
  Test().run()

Notice the capitalization of Username, sessionID and appName must be the same in both your __init__() and your run() methods.

RyanL
  • 458
  • 3
  • 14