Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash pass string argument to python script

I have a bash script which reads variable from environment and then passes it to the python script like this

#!/usr/bin/env bash

if [ -n "${my_param}" ]
then
    my_param_str="--my_param ${my_param}"
fi

python -u my_script.py ${my_param_str}

Corresponding python script look like this

parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--my_param',
                    type=str,
                    default='')

parsed_args = parser.parse_args()
print(parsed_args.description)

I want to provide string with dash characters "Some -- string" as an argument, but it doesn't work via bash script, but calling directly through command line works ok.

export my_param="Some -- string"
./launch_my_script.sh

gives an error unrecognized arguments: -- string and python my_script.py --my_param "Some -- string" works well. I've tried to play with nargs and escape my_param_str="--my_param '${my_param}'" this way, but both solutions didn't work. Any workaround for this case? Or different approach how to handle this?

like image 224
Most Wanted Avatar asked May 19 '16 07:05

Most Wanted


People also ask

Can we pass arguments to Python script?

Many times you need to pass arguments to your Python scripts. Python provides access to these arguments through the sys module. You can directly access the argv functionality and handle the parse of arguments in your own, or you can use some other module as argparse that does that for you.

How do you add arguments to a Python script?

To add arguments to Python scripts, you will have to use a built-in module named “argparse”. As the name suggests, it parses command line arguments used while launching a Python script or application. These parsed arguments are also checked by the “argparse” module to ensure that they are of proper “type”.

How do you pass an argument to a shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.


2 Answers

Your bash needs to look like this:

if [ -n "${my_param}" ]
then
    my_param_str="--my_param \"${my_param}\""
fi

echo ${my_param_str}|xargs python -u my_script.py

Otherwise, the quotes around the parameter string will not be preserved, and "Some", "--" and "thing" will be passed as three separate arguments.

like image 97
cemper93 Avatar answered Sep 28 '22 11:09

cemper93


For the limited example you can basically get the same behavior just using

arg = os.environ.get('my_param', '')

where the first argument to get is the variable name and the second is the default value used should the var not be in the environment.

like image 41
renefritze Avatar answered Sep 28 '22 11:09

renefritze