37

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 Answers3

64

This worked for me:

import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]
Peter Gerhat
  • 1,212
  • 5
  • 17
  • 30
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
F. Ha
  • 51
1
import sys
# Display File name 
print("Script name ", sys.argv[0])
# Display the first argument
print(f"first arg {sys.argv[1]}")
ArunSK
  • 111