0
votes
  • I have a script named first_code.py
  • The code in the script looks like

def function1(param1): return var1 def function2(param1): return var2 def function3(param1): return var3

I want to execute the script first_code.py from the windows command like and pass the value of the param1 such that: all the functions get executed or if I want to execute a specific function say function2.

How can I do that?

2

2 Answers

2
votes

You could use something like this to have a more generalized way to call a function the takes 0-* params :

if __name__ == '__main__':
   print (len(sys.argv))
   params = []
   if len(sys.argv) > 2:
      for x in range(2, len(sys.argv)):
         params.append(sys.argv[x])
   if len(params) > 0:
      globals()[sys.argv[1]](*params)
   else:
      globals()[sys.argv[1]]()

If your script 'getstuff.py' included a function named 'getSomething(forWho, fromWho)' it can be called:
python getstuff.py getsomething "Ray" "Steve"

Can take as many parameters as you want.

Just include the snippet in you script.:>)

1
votes

The arguments you specify in command line are kept in sys.argv you should add the following lines in the bottom of the code:

print function1(sys.argv[1])
print function2(sys.argv[1])
print function3(sys.argv[1])

please note sys.argv[0] is the script name.

If you want to specify the functions to be run add more arguments, they will be in sys.argv[2], sys.argv[3] etc'