简体   繁体   中英

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?

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.

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.

The quotes you write around the string do not get preserved when you assign a Bash string variable:

$ export my_param="Some -- string"
$ echo $my_param
Some -- string

You need to place the quotes around the variable again when you use it to create the my_param_str :

my_param_str="--my_param \"${my_param}\""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM