Search code examples
pythonfunctionexecute

How to start a Python script several functions in


I have a Python script and I want to call it several functions down the script. Example code below:

class Name():

    def __init__(self):
        self.name = 'John'
        self.address = 'Place'
        self.age = '100'

    def printName(self):
        print self.name

    def printAddress(self):
        print self.address

    def printAge(self):
        print self.age

if __name__ == '__main__': 
    Person = Name()
    Person.printName()
    Person.printAddress()
    Person.printage()

I execute this code by entering ./name.py. How could I exectute this code from the function printAddress() down the the end of the script?

Thanks


Solution

  • If you are asking how can you launch your python script and have it start executing at different positions then you will have to launch the script with some information on what you want it to do. The most common way to do this would be to add support for command line arguments.

    import sys
    
    if __name__ == '__main__':   
    
        for arg in sys.argv: 
            print arg
    

    If you were to execute the above script from the command line by itself it would not do anything, but if you launch it with some extra parameters such as

    ./launch.py my_argument another_argument and_so_on
    

    You will see the script has access to the extra launch arguments through the sys.argv list. Using this, you can check for any passed args on launch and then start executing your script at your desired location.

    One example with your script could be as follows

    import sys
    
    class Name:
    
        def __init__(self):
            self.name = 'John'
            self.address = 'Place'
            self.age = '100'
    
        def printName(self):
            print self.name
    
        def printAddress(self):
            print self.address
    
        def printAge(self):
            print self.age
    
    
    if __name__ == '__main__': 
    
        Person = Name()
    
        launchOptions = sys.argv[1:]
    
        if not launchOptions or 'name' in launchOptions:
            Person.printName()
    
        if not launchOptions or 'address' in launchOptions:
            Person.printAddress()
    
        if not launchOptions or 'age' in launchOptions:
            Person.printAge()
    

    The range on the sys.argv[1:] is because the first entry in the sys.argv will be the path to the launched script.

    So you could launch this example and get the following results

    ./launch
    John
    Place
    100
    
    ./launch age
    100
    
    ./launch address
    Place
    
    ./launch name
    John
    

    Now this is just a very basic example. If you are decide to go further in this direction it may be useful for you to read up on pythons getopt module. It's a parser for command line options.

    Hopefully I understood the question correctly.