Using python code in command line with arguments

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mcfly

    Using python code in command line with arguments

    I have a set of python code written up in file.py. Within the code is about 5-6 different functions/sections. What I want to do is execute the python code from the Command Prompt, but only execute the parts that I want to execute. For instance, from the Command Prompt, I would enter ...\file.py [-fun2,fun4] . Entering this would only run section 2 and section 4 in my code. How would I do this?

    Also, expanding on this, I want to enter necessary parameters for my functions that are needed. How would I do this for both the command prompt AND the python code. For example, in my code I have num=43. I would want to go to my command prompt and enter ...\file.py [-fun2] [-num=789]. This would run section 2 and change the num value from 43 to 789. Any help would be appreciated. Thanks
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The script executes at the system command prompt when called. You should design your script to react to parameters. Example:
    Code:
    import sys
    
    def A():
        print "Function 'A'"
    
    def B():
        print "Function 'B'"
    
    if __name__ == "__main__":
        if sys.argv[1].upper() == "A":
            A()
        elif sys.argv[1].upper() == "B":
            B()
        else:
            print "Invalid parameter"

    Comment

    Working...