22

I know how to pass arguments into a shell script. These arguments are declared in AWS datapipeline and passed through. This is what a shell script would look like:

firstarg=$1
secondarg=$2

How do I do this in Python? Is it the exact same?

  • Have you tried to search before you asked? Searching google for passing arguments to python script brings all information you need. As the 4th link I got the question Command Line Arguments In Python from Stackoverflow. – Piotr Dobrogost Oct 23 '15 at 16:36
  • 4
    Searching google for passing arguments to python script brings this post. – Davide Andrea Sep 11 '17 at 22:44
  • So recursion works – Vadim Yangunaev May 15 at 6:16
39

This worked for me:

import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]
| improve this answer | |
  • Yep, that works. For some reason, indexing does not start at 0. So sys.argv[0] is equal to nothing – simplycoding Oct 20 '15 at 16:52
  • 17
    argv[0] should be the script name – Peter Gerhat Oct 20 '15 at 16:54
4

You can use the argv from sys

from sys import argv
arg1, arg2, arg3, ... = argv

You can actually put an abitrary number of arguments in the command line. argv will be a list with the arguments. Thus it can also be called as arg1 = sys.argv[0] arg2 = sys.argv[1] . . .

Keep also in mind that sys.argv[0] is simply the name of your python program. Additionally, the "eval" and "exec" functions are nice when you use command line input. Usually, everything in the command line is interpreted as a string. So, if you want to give a formula in the command line you use eval().

>>> x = 1
>>> print eval('x+1')
2
| improve this answer | |
1
import sys
print("Script name ", sys.argv[0])
print(first arsys.argv[1])
| improve this answer | |
  • 1
    You should enter this in sample.py and call with parameter. – ArunSK May 30 '19 at 16:05
  • ArunSK, you can edit your answer to include your comment. :) – James Skemp Jun 1 '19 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.