0
  • 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 Answers 2

2

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.:>)

Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.