1

Is it possible to pass variables to Python when invoking a script from a bash shell?

For example, when I would call my_script in the shell like this:

python my_script.py -par1 -par2

is it possible to use par1 and par2 as variables in Python so I can pass them as arguments to a function?

Something similar like for shell scripting, where in something like this:

my_script.sh par1

par1 would be stored as $1

2 Answers 2

2

You can get the commandline arguments from sys.argv

Python also comes with a variety of commandline processing utilities. I would recommend argparse which is included in the standard library starting with version 2.7. But there is also optparse or even getopt for the adventurous.

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

Comments

0

Shell:

python my_script.py -par1 -par2

Python: Passing them as arguments to a function:

import sys

arg1,arg2 = sys.argv[1:3]

myfunc(arg1,arg2)

1 Comment

Just to add that sys.argv[0] is the filename and sys.argv[1] is the first argument and so on.

Your Answer

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