1

I want to try simple Python code test.py where I want to pass parameter.

import sys    
result = 3 * 3 * <parameter>
print(result)

When I run the Python code i want to pass value as 3 in input parameter so that i can get result 27 at the end. I can run the python code after passing the value in the parameter. For example i can run the python code like below. Is it possible to do in Python ?

 test.py 3

1 Answer 1

3

You were pretty close with the import sys. The first command-line argument is in sys.argv[1], as a string.

import sys    
result = 3 * 3 * int(sys.argv[1])
print(result)

Example:

~ > python test.py 3
27

Assuming some UNIX-like system, you can run your script as a program (so ./test.py 3) by making it executable and adding a shebang; to run your script from everywhere (so test.py 3), add it to your $PATH. Both of these are optional.

Reference

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

3 Comments

thanks and how can i pass string as parameter ?
It works the same way. python test.py 3 spam 'eggs foo' will mean sys.argv is ['test.py', '3', 'spam', 'eggs foo']. Feel free to experiment.
sorry one more question..for example if i have to pass multiple parameter then how to do that ? For example i have complex code and now i want to pass 3 parameter in different place in my code then does it work in Python ?

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.