How to execute multiline python code from a bash script?
Question:
I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.
result=`python -c "import stuff; print('all $code in one very long line')"`
is not very readable.
I would prefer to specify my python code as a multiline string and then execute it.
Answers:
Use a here-doc:
result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
Tanks to this SO answer I found the answer myself:
#!/bin/bash
# some bash code
END_VALUE=10
PYTHON_CODE=$(cat <<END
# python code starts here
import math
for i in range($END_VALUE):
print(i, math.sqrt(i))
# python code ends here
END
)
# use the
res="$(python3 -c "$PYTHON_CODE")"
# continue with bash code
echo "$res"
This solution might be complex, but working my ubuntu
one line of python script can
- import yaml and sys lib
- lambda-function read yaml file by using first sys.argv1
- get expected value from return nested-dictionary from lambda function by using sys.argv2 sys.argv3
- print yaml_as_dict will load test_var as variable
- check test_var by
echo $test_var
$
$ test_var=$(python3 -c $"import yaml,sys; yaml_as_dict=(lambda :yaml.safe_load(open(f'{sys.argv[1]}','r').read()))()[sys.argv[2]][sys.argv[3]]; print(yaml_as_dict)" <argv1> <argv2> <argv3>)
$
$ echo $test_var
$
How can I put multiple statements in one line?
I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.
result=`python -c "import stuff; print('all $code in one very long line')"`
is not very readable.
I would prefer to specify my python code as a multiline string and then execute it.
Use a here-doc:
result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
Tanks to this SO answer I found the answer myself:
#!/bin/bash
# some bash code
END_VALUE=10
PYTHON_CODE=$(cat <<END
# python code starts here
import math
for i in range($END_VALUE):
print(i, math.sqrt(i))
# python code ends here
END
)
# use the
res="$(python3 -c "$PYTHON_CODE")"
# continue with bash code
echo "$res"
This solution might be complex, but working my ubuntu
one line of python script can
- import yaml and sys lib
- lambda-function read yaml file by using first sys.argv1
- get expected value from return nested-dictionary from lambda function by using sys.argv2 sys.argv3
- print yaml_as_dict will load test_var as variable
- check test_var by
echo $test_var
$
$ test_var=$(python3 -c $"import yaml,sys; yaml_as_dict=(lambda :yaml.safe_load(open(f'{sys.argv[1]}','r').read()))()[sys.argv[2]][sys.argv[3]]; print(yaml_as_dict)" <argv1> <argv2> <argv3>)
$
$ echo $test_var
$
How can I put multiple statements in one line?