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?
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.
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”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With