36

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?

3
  • 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. Oct 23, 2015 at 16:36
  • 7
    Searching google for passing arguments to python script brings this post. Sep 11, 2017 at 22:44
  • 1
    So recursion works May 15, 2020 at 6:16

3 Answers 3

63

This worked for me:

import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]
2
  • Yep, that works. For some reason, indexing does not start at 0. So sys.argv[0] is equal to nothing Oct 20, 2015 at 16:52
  • 24
    argv[0] should be the script name Oct 20, 2015 at 16:54
5

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
1
import sys
# Display File name 
print("Script name ", sys.argv[0])
# Display the first argument
print(f"first arg {sys.argv[1]}")
2
  • 1
    You should enter this in sample.py and call with parameter.
    – ArunSK
    May 30, 2019 at 16:05
  • ArunSK, you can edit your answer to include your comment. :) Jun 1, 2019 at 23:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .